2

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

Bitmap
  • 12,402
  • 16
  • 64
  • 91
Ashish Negi
  • 5,193
  • 8
  • 51
  • 95

5 Answers5

8

You implement Comparable<T>.

From the docs for Collections.sort:

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

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 implement Comparator<T> and pass that in as an extra parameter to Collections.sort

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Your class needs to implement the Comparable interface in order for sort to work.

Dirk
  • 1,893
  • 1
  • 19
  • 26
2

Let your class implement the Comparable interface

b.buchhold
  • 3,837
  • 2
  • 24
  • 33
2

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.

Community
  • 1
  • 1
Richard H
  • 38,037
  • 37
  • 111
  • 138
1

You can either implement Comparable or you can pass a Comparator to Collections.sort

bstick12
  • 1,699
  • 12
  • 18