【发布时间】:2012-10-12 00:12:51
【问题描述】:
今年早些时候,我为我的 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 中打开。