In the sort of Java arrays, collection, and maps, the comparable and comparator interfaces are often used.
1, comparable
We can sort the array by the Arrays.sort () method:
Public Static void Main (string[] args) { int[] intarr={1,5,7,6,3,4}; Arrays.sort (intarr); System.out.println (arrays.tostring (intarr)); /* Output: [1, 3, 4, 5, 6, 7] */ }
Arrays is by transforming the objects in the array into comparable, and then comparing the size by the CompareTo method,
If it is our custom type array, we need to implement the comparable interface to sort by this method.
2, Comparator
Comparable's limitations are also obvious, when we need another rule to sort or reverse order, through comparable can not be implemented, but through the comparator interface, it is easy to solve this problem.
Compared to comparable is implemented within the class, the comparator is implemented externally and has no effect on the original class, so it is much more flexible.
For example, in TreeMap, we can create comparator on demand to determine how to sort:
Public classTest { Public Static voidMain (string[] args) {Comparator<Person> Comparator =NewComparator<person>() {@Override Public intCompare (person O1, person O2) {returnO1.getid ()-O2.getid (); } }; Map<person, string> map =NewTreemap<>(Comparator); Map.put (NewPerson (1), "first"); Map.put (NewPerson (2), "second"); Map.put (NewPerson (4), "third"); Map.put (NewPerson (3), "fourth"); Iterate (map); /*output:key:1;value:first key:2;value:second key:3;value:fourth ke Y:4;value:third*/ } Public Static<K,V>voidIterate (map<k,v>map) { for(Entry<k, v>Entry:map.entrySet ()) {System.out.println ("Key:" +entry.getkey () + "; Value:" +Entry.getvalue ()); } }}classperson{Private intID; PublicPerson (intID) { This. ID =ID; } Public voidSetId (intID) { This. ID =ID; } Public intgetId () {returnID; } @Override PublicString toString () {//TODO auto-generated Method Stub returnId+ ""; }}
Java comparable and comparator