因此,为了允许任何类型对象,我必须在我的代码中使用泛型。
我已经重写了这个方法,但是当我创建一个对象时,例如 Milk,它不会让我将它传递给我的方法。
以太我的通用修订版有问题,或者我创建的 Milk 对象不好。
我应该如何正确传递我的对象并将其添加到链表?
这是一种在我插入项目时会导致错误的方法:
public void insertFirst(T dd) // insert at front of list
{
Link newLink = new Link(dd); // make new link
if( isEmpty() ) // if empty list,
last = newLink; // newLink <-- last
else
first.previous = newLink; // newLink <-- old first
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
这是我尝试插入链表的课程:
class Milk
{
String brand;
double size;
double price;
Milk(String a, double b, double c)
{
brand = a;
size = b;
price = c;
}
}
这是插入数据的测试方法:
public static void main(String[] args)
{ // make a new list
DoublyLinkedList theList = new DoublyLinkedList();
// this causes:
// The method insertFirst(Comparable) in the type DoublyLinkedList is not applicable for the arguments (Milk)
theList.insertFirst(new Milk("brand", 1, 2)); // insert at front
theList.displayForward(); // display list forward
theList.displayBackward(); // display list backward
} // end main()
} // end class DoublyLinkedApp
声明:
class Link<T extends Comparable<T>>
{}
class DoublyLinkedList<T extends Comparable<T>>
{}