你好,所以我有這個任務,我需要實現接口來查看一個ArrayList並對其進行排序(升序或降序)。我不想要「的」答案我只需要一些建議,我的方法,爲什麼我得到這個錯誤實現接口
Exception in thread "main" java.lang.ClassCastException: Week7.Check cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at Week7.TestCheck.main(TestCheck.java:18)
這是我做的:
媲美了一個方法叫public int compairTo(Object o)
:
public class Check implements comparable {
private Integer checkNumber;
public Check(Integer newCheckNumber) {
setCheckNumber(newCheckNumber);
}
public String toString() {
return getCheckNumber().toString();
}
public void setCheckNumber(Integer checkNumber) {
this.checkNumber = checkNumber;
}
public Integer getCheckNumber() {
return checkNumber;
}
@Override
public int compairTo(Object o) {
Check compair = (Check) o;
int result = 0;
if (this.getCheckNumber() > compair.getCheckNumber())
result = 1;
else if (this.getCheckNumber() < compair.getCheckNumber())
result = -1;
return result;
}
}
在我的主
我有這個
import java.util.ArrayList;
import java.util.Collections;
public class TestCheck {
public static void main(String[] args) {
ArrayList checkList = new ArrayList();
checkList.add(new Check(445));
checkList.add(new Check(101));
checkList.add(new Check(110));
checkList.add(new Check(553));
checkList.add(new Check(123));
Collections.sort(checkList);
for (int i = 0; i < checkList.size(); i++) {
System.out.println(checkList.get(i));
}
}
}
我猜你的意思是標籤的Java而不是JavaScript,因此我重新標記它。 – 2010-05-15 18:37:13
請記得把你的代碼放在一個代碼塊 – Galen 2010-05-15 18:38:06
我不確定它是否只是複製錯誤,但我認爲它應該是可比較的不可比較的 – 2010-05-15 18:44:55