我今年早些时候为我的java类编写了一个链表实现.这是一个名为LList的泛型类.我们现在必须为实验室写出合并排序算法.我决定只重用之前创建的通用列表,而不是创建一个需要Ints的新List实现.
问题是如何比较两个通用对象?java不会让我做类似的事情
if(first.headNode.data > second.headNode.data)
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,他们是一种实现某种比较函数的方法,它可以处理任何类型的数据吗?我尝试了以下方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
哪个甚至都不能正常工作.我用数字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;
}
Run Code Online (Sandbox Code Playgroud)
注意:整个LList类可以在[这里]找到(http://rapidshare.com/files/219112739/LList.java.html MD5:BDA8217D0756CC171032FDBDE1539478)
请注意,Comparable也是一种泛型类型,按其可比的类型进行参数化.上面声明mergeSort函数的最通用,类型安全的方法是:
private <T extends Comparable<? super T>> LList<T> mergeSort(LList<T> list) { }
Run Code Online (Sandbox Code Playgroud)
这强制了类型T的compareTo方法可以接受类型为T的参数.(理论上,类型可以实现Comparable,但不能与其自身相比SomeClass implements Comparable<CompletelyDifferentClass>,因此对Comparable的类型参数有要求很重要.然而,在实践中,任何精心设计的可比较类都应该至少与其自身相当.)
我们要求<T extends Comparable<? super T>>而不仅仅是<T extends Comparable<T>>因为类型T的compareTo方法接受比T更通用的类型是可以的,因为它仍然能够接受类型为T的参数.这很重要因为,如果你有一个类A,实施Comparable<A>; 然后你有一个子类B,它扩展了A,B不能实现Comparable<B>,因为B已经实现Comparable<A>,继承自A,而一个类不能实现两次接口.因此,如果我们<T extends Comparable<T>>上面要求,B将不满足它,我们将无法对LList<B>对象进行排序.
| 归档时间: |
|
| 查看次数: |
12651 次 |
| 最近记录: |