[英]How to use Comparator<T> as an argument in a generic SortedDoublyLinkedList
我目前正在為一個類分配,我的任務是創建一個空的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>
(或您選擇的任何類型)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.