Java Sorting: sort an array of objects by property, object not allowed to use Comparable

You can provide a Comparator for comparing any type you wish, Comparable or otherwise. For Arrays and Collections you use Arrays.sort(array, myComparator); Collections.sort(list, myComparator); Even sorted collections like TreeSet can take a custom Comparator e.g. Collections.sort(books, new Comparator<Book>() { public int compare(Book b1, Book b2) { return if b1 is greater return +1, if b2 … Read more

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn’t follow this principle?

Here’s a simple but realistic example of what can happen if a comparison method is inconsistent with equals. In the JDK, BigDecimal implements Comparable but its comparison method is inconsistent with equals. For example: > BigDecimal z = new BigDecimal(“0.0”) > BigDecimal zz = new BigDecimal(“0.00”) > z.compareTo(zz) 0 > z.equals(zz) false This is because … Read more

Comparable and Comparator contract with regards to null

Comparable doesn’t allow null simply because: a.compareTo(b) == -b.compareTo(a) for all objects a and b where !a.equals(b). More specifically: a.equals(b) ? b.equals(a) && a.compareTo(b) == 0 && b.compareTo(a) == 0 && a.hashCode() == b.hashCode() : !b.equals(a) && a.compareTo(b) != 0 && a.compareTo(b) == -b.compareTo(a) must evaluate to true to satisfy the relevant contracts. So null … Read more

How do I make 2 comparable methods in only one class?

What you need to do is implement a custom Comparator. And then use: Collections.sort(yourList, new CustomComparator<YourClass>()); Specifically, you could write: (This will create an Anonymous class that implements Comparator.) Collections.sort(yourList, new Comparator<YourClass>(){ public int compare(YourClass one, YourClass two) { // compare using whichever properties of ListType you need } }); You could build these into … Read more