In our usual use of collection, it is very often necessary to sort the elements inside. For this sort, there are usually two ways to implement this:
1. Create a comparator class to implement the comparator interface, and then apply the sort method provided by the collection internally. For example, the edges in the graph are sorted by their weight size (the second method is also described in the following example).
The Edge Edge is implemented as follows:
public class edge{
Vertex s,t;
Double weight;
。。。
}
We implement the comparator class definition as follows:
The methods for sorting are as follows:
public void sort (list<edge> edges) {
Edgecomparator comparator = new Edgecomparator ();
Collections.sort (Edges,comparator);
}
This allows us to sort the edge in edges by the size of its weights. In our practical application, you can adjust it according to your own needs.
2. Let your ADT implement the comparable interface, and then override the CompareTo () method. The difference between this approach and comparator is that there is no need to construct a new comparator class, and the comparison code is placed inside ADT.
Thus we rewrite the following edge classes as defined above:
Then apply collections.sort (edges) to sort the edges.
Ordering of elements within Collection,arrays in Java (Application of Comparable,comparator interface)