看板Programming
标 题[问题]Java中,如何implements Comparable?
发信站梦之大地 (Fri Jun 8 21:27:01 2007)
转信站ptt!ctu-reader!ctu-gate!news.nctu!news2!ccnews.ncku!Dream
一个我写的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