Java class problem
In C++ if we add some class objects to vector , we can sort the list by specifying some functions like operator<() or operator==() or operator!=.
What do we need to do in java for Collections.sort to work according to our wishes
Java class problem
In C++ if we add some class objects to vector , we can sort the list by specifying some functions like operator<() or operator==() or operator!=.
What do we need to do in java for Collections.sort to work according to our wishes
Your class needs to implement the Comparable interface in order for
sort
to work.You can either implement Comparable or you can pass a Comparator to Collections.sort
You need to write a Comparator - typically you just override the compare method which returns an int, +ve, 0 or -ve to indicate "greater than", "the same" or "less than" for whatever definitions of these you choose. See another of my answers for an example.
You implement
Comparable<T>
.From the docs for
Collections.sort
:Alternatively, if you don't control the element type (e.g. you've got a
List<String>
and you want to apply a custom sort order) you implementComparator<T>
and pass that in as an extra parameter toCollections.sort
Let your class implement the Comparable interface