我有一些代码:
Collection<MyGraph.MyVertex> vertCollection = graph.getVertices();
其中getVertices是JUNG包的一部分,其定义如下:
public interface Hypergraph<V, E> {
Collection<E> getEdges();
Collection<V> getVertices();
...
...
}
> If I print out the collection I may get something like [v1,v2,v4,v3]
> and on another run something like [v2,v3,v1,v4]
这使我每次都以随机顺序返回顶点列表。因此,我在代码其他地方的结果是不可重复的,并且很难跟踪。
我想每次都以相同的方式将元素重新排序。我目前的猜测是,我必须将集合转换为保留顺序的某种数据结构,然后对其进行排序,以便结果可重复,但是有更好的方法吗? (我不确定从Collection转换为数组之类的其他东西是否会破坏代码,因为我是Collection的新手。)任何帮助都会很棒!
您可以使用类似这样的内容:
List<String> names = Arrays.asList("Alex", "Charles", "Brian", "David");
//Natural order
Collections.sort(names); //[Alex, Brian, Charles, David]
//Reverse order
Collections.sort(names, Collections.reverseOrder()); [David, Charles, Brian, Alex]
只需使用ArrayList来实现Collection。 ArrayList的行为就像一个数组。它们以与放入时相同的顺序出现。
简单地将Collection
转换/转换为List(有序集合),然后您可以根据需要应用Collections.sort。