java - 自制泛型List类转换错误

标签 java list generics

此代码出现转换错误,我不确定为什么会发生。

错误是:

List.java:131: error: incompatible types: Comparable cannot be converted to T
      this.insertAtFront(remove.firstNode.data);

它出现在使用 List 中的 .data 作为 ListNode 的代码的每个部分中。

我标记了发生错误的行。

有什么想法吗?

public class List<T extends Comparable<T>> {

private ListNode firstNode;
private ListNode lastNode;
private String name;

public List(String listName){
    name=listName;
    firstNode=lastNode=null;
}

public T removeAt(int k) throws ListIndexOutOfBound {
    List remove = new List();
    T o;
    if(k < 0 || k > checkSize()) throw new ListIndexOutOfBound();
    for(int i = 0; i < k; i++){
        try {
            remove.insertAtFront(firstNode.data);
            this.removeFromFront();
        } catch (Exception e) {
            while(!remove.isEmpty()){
                this.insertAtFront(**remove.firstNode.data**);
                remove.removeFromFront();
            }
            throw new ListIndexOutOfBound();
        }
    }
    **o = firstNode.data;**
    this.removeFromFront();
    while(!remove.isEmpty()){
        this.insertAtFront(**remove.firstNode.data**);
        remove.removeFromFront();
    }
    return o;
}
}

这是 ListNode 类:

public class ListNode<T extends Comparable<T>> {

T data;
ListNode nextNode;

public ListNode(T o){
    this(o,null);
}

public ListNode(T o, ListNode node){
    data = o;
    nextNode = node;
}

public T getObject(){
    return data;
}
}

最佳答案

当你查看你的List类时,你会发现firstNode和lastNode的定义都不包含泛型类型信息!

所以将其更改为

ListNode<T> firstNode 

这个问题应该就会消失。创建“删除”列表时也是如此。

省略通用信息会创建所谓的原始类型。每次这样做时您都会收到警告。不要忽略该警告 - 只需修复所有使用原始类型的地方即可!

关于java - 自制泛型List类转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870783/

相关文章:

java - 将 JScrollPane 添加到覆盖的 JPanel

c# - 优化获取下一个值列表函数

c# - 从方法返回 List<T> 的性能是否与返回 Collection<T> 不同?

c# - 使用通用抽象类型参数和链接的 .net 单元测试

java - macOS 上的 Eclipse 安装

Java用SWT实现MVC

java - 将十六进制字符串转换为 byte[] 数组时出现错误 "java.lang.StringIndexOutOfBoundsException"

python - 如何从列表项制作嵌套字典?

c# - 为什么我不能将 List<List<Foo>> 传递给 IEnumerable<IEnumerable<Foo>>

java - 在类中传递通用对象类型