今年早些時候,我爲我的java類寫了一個鏈表實現。這是一個名爲LList的通用類。我們現在必須寫出實驗室的合併排序算法。我沒有創建一個採用Ints的新List實現,而是決定重用我之前創建的通用列表。比較通用列表中的元素
問題是如何比較兩個通用對象? 的Java不會讓我這樣做
if(first.headNode.data > second.headNode.data)
所以,我的問題是,是他們實現某種比較函數將在任何類型的數據的工作方式?我嘗試了以下內容:
String one, two;
one = first.headNode.data.toString();
two = second.headNode.data.toString();
if(first.headNode.data.compareTo(second.headNode.data) < 0) {
result.add(first.headNode.data);
// remove head node. remove() takes care of list size.
first.remove(1);
} else {
// If compareTo returns 0 or higher, second.headNode is lower or
// equal to first.headNode. So it's safe to update the result
// list
result.add(second.headNode.data);
second.remove(1);
}
哪個甚至不能正常工作。我用數字6和12進行了測試,上面在結果列表中增加了12。
相關的東西:
private LList<T> mergeSort(LList<T> list) {
LList<T> first = new LList();
LList<T> second = new LList();
if (list.length() == 1) {
return list;
}
int middle = list.length()/2;
second.headNode = list.getNodeAt(middle + 1);
second.length = list.length() - (middle);
// Set first half to full list, then remove the "second" half.
first.headNode = list.headNode;
first.length = middle;
first.getNodeAt(middle).next = null;
// Get the splitted halves.
first = mergeSort(first);
second = mergeSort(second);
return merge(first, second);
}
private LList<T> merge(LList<T> first, LList<T> second) {
LList<T> result = new LList();
while((first.length > 0) && (second.length > 0)) {
// Ok, lets force toString to compare stuff since generics are a pain.
String one, two;
one = first.headNode.data.toString();
two = second.headNode.data.toString();
if(one.compareTo(two)) < 0) {
result.add(first.headNode.data);
// remove head node. remove() takes care of list size.
first.remove(1);
} else {
// If compareTo returns 0 or higher, second.headNode is lower or
// equal to first.headNode. So it's safe to update the result
// list
result.add(second.headNode.data);
second.remove(1);
}
}
return result;
}
注意:整個LLIST類可以找到[這裏](http://rapidshare.com/files/219112739/LList.java.html MD5:BDA8217D0756CC171032FDBDE1539478)
如果您想「欺騙」,請查看Java源代碼,以獲取類似Collections.sort()的內容。當你安裝JDK時,應該有一個選項來安裝源代碼。然後在安裝目錄中會有一個src.jar文件。 .jar文件可以重命名爲.zip並在WinZip中打開。 – Kip 2009-04-09 02:18:24