我目前正在为一个类分配,我的任务是创建一个空的List,它有一个Comparator作为参数,然后为那个sortedDoublyLinkedList创建一个add方法,我传递了一个参数,我必须遍历列表找到哪里新节点适合。我对比较器不太熟悉所以我对如何将元素添加到我的DoublyLinkedList有点无能为力,因为我不能按照我应该的方式访问比较器。这就是我现在拥有的。这是我现在拥有的。
public class SortedDoubleLinkedList<T> extends BasicDoubleLinkedList<T> {
Node<T> head=null;
Node<T> tail=null;
SortedDoubleLinkedList<T> sDLL;
public SortedDoubleLinkedList(Comparator<T> comparator2){
sDLL=new SortedDoubleLinkedList<T>(comparator2);
}
public SortedDoubleLinkedList<T> add(T data){
Node<T> newNode=new Node<T>(data);
//I have to iterate through the list and find where the new element data fits
if(head!=null&&tail!=null) {
Node<T> cursor=head;
while(cursor!=null) {
//the following code doesn't work
if(sDLL.comparator2.compare(data, cursor.getData())==0) {
}
}
}
else {
head=newNode;
tail=newNode;
}
return this; //return the SortedDoubleLinkedList<T>
}
比较器是一个接口。您需要实现一个将提供该接口的类。
class Whatever implements Comparator<TYPE> {
int compare(TYPE a, TYPE b) {
... code to decide whether a is less than,
equal to, or greater than b ...
}
}
在我写TYPE的地方,你需要一个实际的类型。只提供类型变量T不会让你得到可运行的代码,我认为这是你的目标。最终你必须说出你的清单中会有什么类型。所以我会期待类似的东西(在上面的代码中)
public class SortedDoubleLinkedList extends BasicDoubleLinkedList<String> {
您在列表中存储字符串的位置。然后我的代码中的TYPE也是String。
另外
您可以将SortedDoubleLinkedList保留为通用(就T而言),但最终您可能希望得到具体的信息
SortedDoubleLinkedList<String> = new SortedDoubleLinkedList(new Whatever());
但Comparator
仍然需要成为Comparator<String>
(或您选择的任何类型)。