所以我试图在Doubly Linked列表中添加一些字符串,但我不断收到String无法转换为PubliclyCloneable的错误(扩展Cloneable的接口,用于创建clone()和复制构造函数,我的教科书的解释)。这是我的演示代码:
public static void main(String[] args)
{
DoublyLinkedList list1 = new DoublyLinkedList();
DoublyLinkedList.DoublyLinkedIterator i = list1.iterator();
String pittsburgh1 = new String("Penguins");
String pittsburgh2 = new String("Pirates");
String pittsburgh3 = new String("Steelers");
list1.addToStart(pittsburgh1);
list1.addToStart(pittsburgh2);
list1.addToStart(pittsburgh3);
System.out.println("List contains:");
i.restart();
while (i.hasNext())
System.out.println(i.next());
System.out.println("");
这是DoublyLinkedList类的开头部分:
public class DoublyLinkedList<T extends PubliclyCloneable> implements PubliclyCloneable
{
private class TwoWayNode<T>
{
private T data;
private TwoWayNode<T> next;
private TwoWayNode<T> prev;
public TwoWayNode()
{
data = null;
next = null;
prev = null;
}
public TwoWayNode(T newData, TwoWayNode<T> prevNode, TwoWayNode<T> nextNode)
{
data = newData;
next = nextNode;
prev = prevNode;
}
}
以下是导致编译器错误的方法:
public void addToStart(T itemData)
{
TwoWayNode<T> newHead = new TwoWayNode(itemData, null, head);
if (head != null)
{
head.prev = newHead;
}
head = newHead;
}
这是我正在使用的界面:
public interface PubliclyCloneable extends Cloneable
{
public Object clone();
}
所以我可能会在这里忽略一些东西,但我正在努力实现哪些目标呢?是否有某种类型转换或类型赋值可以将这三个字符串添加到我的列表中?
答案 0 :(得分:0)
您正在尝试将字符串添加到您声明将保留PubliclyCloneable的列表中。将PubliclyCloneable对象放入其中或声明它将保存字符串。
答案 1 :(得分:0)
您的addToStart
方法接受T
类型的参数,其中T
由类定义为T extends PubliclyCloneable
。
由于java.lang.String
未实现PubliclyCloneable
,因此它不能是DoublyLinkedList
的参数类型。如果你想要一个main
函数来测试你的类,我会实现一个简单的愚蠢PubliclyClonableString
类::
public class PubliclyClonableString implements PubliclyClonable {
private String s;
public PubliclyClonableString (String s) {
this.s = s;
}
@Override
public String clone() {
return s; // OK, since Strings are immutable
}
// getter, setter, etc.
}
答案 2 :(得分:0)
由于DoublyLinkedList
需要一个扩展PubliclyCloneable
的类,因此您必须创建自定义字符串类:
public class CloneableString implements PubliclyCloneable {
private String str;
public CloneableString(String str) {
this.str = str;
}
public String getString() {
return str;
}
@Override
public Object clone();
return new CloneableString(str);
}
}