[問題]Java中,如何implements Comparable?
一個我寫的Java class如下:
public class InventoryItem implements Comparable
{
....
因為要implements Comparable
必須override compareTo():
public int compareTo(Object other)
{
return 0;
}
又因為要比較裡面private資料ID的大小
所以又overload它,使其達到我的要求
public int compareTo(InventoryItem item)
{
return this.getID() - item.getID();
}
....
}
現在問題來了
我在主程式中建立了InventoryItem的array物件item
想將它們依照ID來做排列,寫了一個用Comparable做的sort
//modified bubble sort
private static void sort(Comparable[] a, int numberUsed)
{
for(int index = 0; index < numberUsed - 1; index++)
for(int i = 0; i < numberUsed - 1 - index; i++)
if(a[i].compareTo(a[i + 1]) > 0) //<--here is the problem
exchange(i, i + 1, a);
}
結果在a[i].compareTo(a[i + 1])這裡出了差錯
我利用輸出的方式檢查,所有傳回的值都是零
這代表我寫的InventoryItem並不算是一種Comparable type嗎?
還是說implements的方法或是其他地方有誤呢?
另外,不管如何,只要有a[i].compareTo(a[i + 1])出現
compiler就會警告我
可是我拿去試wrapping class的type都是可用的(ex: Double, Integer...)
這是為什麼呢?(編譯環境為Blue Java)
希望熟悉Java語言的人能替我解惑,謝謝
--
◢◣ ︵︵ █▔◣ █▔█ █▔▔ █▔█ █▆▉ █ █▔█ █◣█ █▔●
◢◤█◣◢◣ ︵︵ █ █ █▁◤ █▁▁ █▁█ ▉▉▉ █ █▁█ █◥█ █ █
夢之大地 逼逼ㄟ四 █▁◤ █ █ █▁▁ █ █ ▉▉▉ █▁ █ █ █ █ █▁◤
※ Origin: <bbs.ccns.ncku.edu.tw> ◆ From: 140.116.101.13
討論串 (同標題文章)
Programming 近期熱門文章
PTT數位生活區 即時熱門文章