首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个java程序出错了吗?

这个java程序出错了吗?
EN

Stack Overflow用户
提问于 2014-09-20 05:32:48
回答 1查看 3.9K关注 0票数 1

我试图在java中为链接列表创建一个泛型类,并且我面临一些无法调试的错误。

代码:

代码语言:javascript
复制
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;   
    }

}

我对仿制药没有多少经验。这是我正在犯的错误:

代码语言:javascript
复制
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可以是不同类型的,但我不知道如何纠正它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-20 05:38:50

您需要将<T>addremove方法的声明中删除,因为通过编写以下内容

代码语言:javascript
复制
public <T> void add (T x)

您保存的变量x可以是任意类型的T,但是当您试图在此方法中进行赋值时,问题就出现了。

代码语言:javascript
复制
this.current.value=x;

您的类型不兼容,current的类型与x的类型不同,为什么?由于用于声明Tcurrent与用于声明xT不同,因此您将得到错误。删除<T>,它应该可以工作

像这样

代码语言:javascript
复制
  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;   
    }

也是在静态变量的声明中

代码语言:javascript
复制
static node<T> head,last;

您有编译器错误,因为LinkedList.this不能从静态上下文中引用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25945594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档