Re: [問題]Java中,如何implements Comparable?

看板Programming作者 (ephesians)時間18年前 (2007/06/09 11:30), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《HentaiFirst.bbs@bbs.ccns.ncku.edu.tw (我真的一點也不糟糕!)》之銘言: : 一個我寫的Java class如下: : public class InventoryItem implements Comparable (略) : 必須override compareTo(): : public int compareTo(Object other) (略) : 所以又overload它,使其達到我的要求 : public int compareTo(InventoryItem item) (略) : 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嗎? 粗淺地猜測,會不會是因為compareTo的方法署名為: public int compareTo(Object other) 而你的實作 public int compareTo(InventoryItem item) 並不完全覆寫Comparable介面的方法. 也許可以加上這個覆寫: public int compareTo(Object other) { compareTo((InventoryItem)other); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.160.215.118
文章代碼(AID): #16QXxcAe (Programming)
文章代碼(AID): #16QXxcAe (Programming)