简体   繁体   English

奇怪的错误,试图在Java中创建一个通用的链表类

[英]weird error, trying to create a generic linked list class in java

public class GenericLinkedList<T extends Comparable<T>> implements Cloneable {

GenericListNode<T> head;

/**
 * inserts a new node containing the data toAdd at the given index.
 * @param index
 * @param toAdd
 */
public <T> void add (int index, T toAdd) {
    GenericListNode<T> node = new GenericListNode<T>((T) toAdd);
    if (isEmpty()) {
        head = node;
    } else {

    }

}

This is the code I have and for some reason it has a problem with me doing 这是我的代码,由于某种原因,我在执行时遇到了问题

head = node;

It says: 它说:

Type mismatch: cannot convert from GenericListNode<T> to GenericListNode <T extends Comparable<T>>

It suggests Casting node to be 建议将Casting节点设置为

head = (GenericListNode<T>) node;

But it still gives me the error. 但这仍然给我错误。

In this declaration 在此声明中

public <T> void add

you are defining a new type called T that is completely independent from the T defined at the class level. 您正在定义一个称为T的新类型,该类型与在类级别定义的T完全独立。 That's the notation for declaring a generic method. 这就是声明通用方法的表示法。

Since the two types don't have the same bounds, they are not compatible and one cannot be converted to the other. 由于这两种类型没有相同的界限,因此它们不兼容,并且一种不能转换为另一种。

Get rid of that generic declaration. 摆脱通用声明。

Don't redefine T in your method: 不要在您的方法中重新定义T

public void add (int index, T toAdd) {
    GenericListNode<T> node = new GenericListNode<T>((T) toAdd);
    if (isEmpty()) {
        head = node;
    } else {

    }
}

T is already defined at "class-level", if you add it again on the method you are hiding the class-level one, thus you have two different types called T . T已经在“类级别”定义了,如果您再次将其添加到隐藏类级别的方法上,则将有两种不同的类型称为T

You are re-defining (read: shadowing) the generic definition of T . 您正在重新定义(阅读:阴影) T的一般定义。 Just drop it from the method definition and you should be fine: 只需将其从方法定义中删除,就可以了:

public class GenericLinkedList<T extends Comparable<T>> implements Cloneable {

    GenericListNode<T> head;

    /**
     * inserts a new node containing the data toAdd at the given index.
     * @param index
     * @param toAdd
     */
    public void add (int index, T toAdd) {
        GenericListNode<T> node = new GenericListNode<T>(toAdd);
        if (isEmpty()) {
            head = node;
        } else {

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM