2013-01-21 78 views
0

我有我的用户定义类的列表。比较在Arraylist

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; 
    } 
}); 

现在我的年龄可变可能有值或年龄客户的。所有null值应该是追加在最后,其余的值应该排序在升序或降序(任何事都可以)?

但是这个代码是抛出异常:

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

请告诉我该怎么办? 在此先感谢。

+1

全堆栈跟踪请... – Andremoniy

+0

看看http://stackoverflow.com/questions/8327514/comparison-method-violates-其一般合同 – cubbuk

回答

3

当且仅当c.compare(e1,e2)== 0具有与e1.equals相同的布尔值时,由比较器c对一组元素S施加的顺序被认为与等于一致(E2)为>在S.

每e1和e2

价 - link

元组必须一致。不一致的平等会表现得很糟糕。

+0

我明白这一点,但最新的解决方案........... –

1

如果只有一个顾客有年龄而另一个顾客没有年龄,那么你不能正确处理这些情况。

此外,在其他情况下返回1似乎是不正确的。如果根据年龄没有差异,则返回0而不是1.