2013-05-07 95 views
0

我之前问compare arraylists of chars alphabetically如何按字母顺序比较字符的arraylists。 现在我决定实施它。比较方法违反其总体合同(arraylist comprasion)

这里是我的comprasion方法

@Override 
public int compareTo(Word o) { 

    int left = this.count(); 
    int right = o.count(); 

    if (left == right){ 
     if (this.length() > o.length()){ 
      try{ 
       for(int i = 0; i < this.length(); i++){ 
        if (this.get(i).compareTo(o.get(i)) < 0) 
         return 1; 
       } 
      }catch(IndexOutOfBoundsException e){ 
       return -1; 
      } 
     } 

     else { 
      try{ 
       for(int i = 0; i < o.length(); i++){ 
        if (this.get(i).compareTo(o.get(i)) < 0) 
         return -1; 
       } 
      }catch(IndexOutOfBoundsException e){ 
       return 1; 
      } 
     } 
    } 
    else return (left > right)?1:-1; 
    return 0; 
} 

我检查this.count是否等于o.count,如果没有我开始的ArrayList中的每个元素进行比较。但如果它不相等,那么我会比较leftright

但我不明白为什么会抛出这样的异常。哪里有问题?

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract! 
at java.util.ComparableTimSort.mergeHi(Unknown Source) 
at java.util.ComparableTimSort.mergeAt(Unknown Source) 
at java.util.ComparableTimSort.mergeCollapse(Unknown Source) 
at java.util.ComparableTimSort.sort(Unknown Source) 
at java.util.ComparableTimSort.sort(Unknown Source) 
at java.util.Arrays.sort(Unknown Source) 
at java.util.Collections.sort(Unknown Source) 
    at task.Main.main(Main.java:69) 

Main.java: 69就是Collections.sort invoked`。

+0

如果您提供您看到的实际例外情况,这可能会有所帮助。 – jpmc26 2013-05-07 23:32:54

回答

1

一些评论:

if (this.get(i).compareTo(o.get(i)) < 0) 
    return 1; 

这应该返回-1

catch(IndexOutOfBoundsException e){ 
    return -1; 
} 

这1(因为this尺寸越大)

catch(IndexOutOfBoundsException e){ 
    return 1; 
} 

这-1(因为this大小较小)

请尝试使用这些更改。

相关问题