我试图在java中为链接列表创建一个泛型类,并且我面临一些无法调试的错误。
代码:
class node<T>
{
T value;
node<T> next;
}
class LinkedList<T>
{
static node<T> head,last;
static int no;
node<T> current=new node<T>();
public <T> void add(T x)
{
this.current.value=x;
this.current.next=null;
last.next=this.current;
last=this.current;
if(no==0)
head=this.current;
no++;
}
public <T> T remove()
{
node<T> y=head;
while(y.next.next!=null)
{
y=y.next;
}
T z =y.next.value;
y.next=null;
last=y;
return z;
}
}我对仿制药没有多少经验。这是我正在犯的错误:
linkedlist.java:14: error: incompatible types
this.current.value=x;
^
required: T#2
found: T#1
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>add(T#1)
T#2 extends Object declared in class LinkedList
linkedlist.java:25: error: incompatible types
node<T> y=head;
^
required: node<T#2>
found: node<T#1>
where T#1,T#2 are type-variables:
T#1 extends Object declared in class LinkedList
T#2 extends Object declared in method <T#2>remove()
linkedlist.java:32: error: incompatible types
last=y;
^
required: node<T#2>
found: node<T#1>
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>remove()
T#2 extends Object declared in class LinkedList
3 errors我知道错误是因为在这种情况下T可以是不同类型的,但我不知道如何纠正它。
发布于 2014-09-20 05:38:50
您需要将<T>从add和remove方法的声明中删除,因为通过编写以下内容
public <T> void add (T x)您保存的变量x可以是任意类型的T,但是当您试图在此方法中进行赋值时,问题就出现了。
this.current.value=x;您的类型不兼容,current的类型与x的类型不同,为什么?由于用于声明T的current与用于声明x的T不同,因此您将得到错误。删除<T>,它应该可以工作
像这样
public void add(T x)
{
this.current.value=x;
this.current.next=null;
last.next=this.current;
last=this.current;
if(no==0)
head=this.current;
no++;
}
public T remove()
{
node<T> y=head;
while(y.next.next!=null)
{
y=y.next;
}
T z =y.next.value;
y.next=null;
last=y;
return z;
}也是在静态变量的声明中
static node<T> head,last;您有编译器错误,因为LinkedList.this不能从静态上下文中引用。
https://stackoverflow.com/questions/25945594
复制相似问题