0

I have a List of my user defined class.

class Customer{
  Integer age;
  String name;
  //getter & setter
}


Collections.sort(customerList, new Comparator <Customer>() {        
  public int compare(Customer o1, Customer o2) {
    // TODO Auto-generated method stub              
    if(o1.getAge()!=null && o2.getAge() != null)
        return o1.getDistance().compareTo(o2.getDistance());
    else
      return 1;
  }
});

Now my age variable may have a null value or the age of the customer. All null values should be appended at the end and remaining values should sorted in ascending or descending order(anything is ok)?

But this code is throwing an exception :

java.lang.IllegalArgumentException: Comparison method violates its general contract!

Please tell me what to do? Thanks in advance.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Ankur Verma
  • 5,793
  • 12
  • 57
  • 93

2 Answers2

3

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for >every e1 and e2 in S.

Ref - link

Element set must be consistent. Inconsistent equals will behave straggly.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

You are not handling the cases correctly where only one of the customers has an age and the other has not.

Also, returning 1 in the else-situation seems to be incorrect. If there is no difference according to the age, then return 0 instead of 1.

gogognome
  • 727
  • 8
  • 24