Collections.sort - IllegalArgumentException:比较方法违反了其一般合同

时间:2016-08-17 12:15:22

标签: java android sorting collections

我们的一些用户在排序列表时遇到此异常。抛出它的代码是

Collections.sort(activeConverstions, new Comparator<Conversation>() {
        @Override
        public int compare(Conversation o1, Conversation o2) {
            return (int)(o2.getTime()- o1.getTime()); // descending order
        }
    });

而getTime()的类型为&#34; long&#34;

3 个答案:

答案 0 :(得分:5)

该问题可能会将long转换为int,这可能会将较大的long号码转换为否定的int

例如,请考虑以下代码段:

long first = Integer.MAX_VALUE + 1;
long second = 0;
System.out.println((int) (first - second));
System.out.println((int) (second - first));

输出:

-2147483648
-2147483648

如果您要将compare方法传递给两个Conversation个实例 - 让我们称他们为xy - 其getTime()等于{{1}分别在上面的代码段中{}}和firstsecondcompare(x,y)都会返回一个负值,这违反了该方法的合同。

尝试:

compare(y,x)

或者,如同assylias建议:

Collections.sort(activeConverstions, new Comparator<Conversation>() {
    @Override
    public int compare(Conversation o1, Conversation o2) {
        return o2.getTime() > o1.getTime() ? 1 :  o2.getTime() < o1.getTime() ? -1 : 0;
    }
});

答案 1 :(得分:2)

实现sql=`DROP TABLE IF EXISTS cliente; CREATE TABLE cliente (id INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT, telefono TEXT); DROP TABLE IF EXISTS parte; CREATE TABLE parte (id INTEGER PRIMARY KEY AUTOINCREMENT, clienteid INTEGER CONSTRAINT fk_clienteid REFERENCES cliente (id) ON DELETE CASCADE ON UPDATE SET DEFAULT, fecha DATE NOT NULL, horaini TIME NOT NULL, horafin TIME NOT NULL, trabajorealizado TEXT, personafirma TEXT);`; this.storage.query(sql); 方法的最佳做法是仅返回-1,0或1。

compare

修改

正如@assylias所说,使用已经实现的比较方法更好:

    Collections.sort(activeConverstions, new Comparator<Conversation>() {
        @Override
        public int compare(Conversation o1, Conversation o2) {
            long result = o2.getTime()- o1.getTime();
            return result < 0 ? -1 : result > 0 ? 1 : 0;
        }
    });

答案 2 :(得分:2)

你可以试试这个

 Collections.sort(activeConverstions, 
    new Comparator<Conversation>()            {
    @Override
    public int compare(Conversation o1, Conversation o2) {
    if ((o2.getTime() > o1.getTime())
      return 1;
    else  if ((o2.getTime() < o1.getTime())
     return -1;
    else return 0;
    }
 });