简体   繁体   中英

Comparator in Arraylist

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM