gpt4 book ai didi

java - 使用泛型时出现类型不兼容错误

转载 作者:行者123 更新时间:2023-12-02 03:43:38 25 4
gpt4 key购买 nike

我有这个链表类实现LinkedList,其中包含一个方法getMode

public class LinkedList<AnyType extends Comparable<? super AnyType>>
{

//Some code...

public AnyType mode(){

//Some code...

ListNode node;
AnyType mode;

mode = node.element;
return mode;
}
}

泛型变量 AnyType 在此链表类中进行类型绑定(bind)。相同的变量绑定(bind)在另一个类 ListNode 中。 LinkedList 中未声明 ListNode。它是一个独立的类。

class ListNode<AnyType extends Comparable<? super AnyType>>
{

//Some code...

public AnyType element;
}

我想知道为什么链表类中的行

mode = node.element;

给我一​​个类型不兼容错误

>Required AnyType
Found java.lang.Comparable < >

通用 AnyType 变量的类型界限在节点类和链表类中是相同的,所以我不明白为什么这里应该存在类型不兼容。

类型绑定(bind)始终是

 <AnyType extends Comparable<? super AnyType>>

编辑

有人提到了一个似乎有效的解决方案。我必须在 getMode 方法中指定 AnyType 作为节点节点变量的绑定(bind),否则将使用原始类型或类似的内容

public class LinkedList<AnyType extends Comparable<? super AnyType>>
{

//Some code...

public AnyType mode(){

//Some code...

ListNode<AnyType> node; // <--- here
AnyType mode;

mode = node.element;
return mode;
}
}

最佳答案

因为编译器不知道AnyType来自您的LinkedListAnyType 相同在你的ListNode

例如,LinkedList<String>ListNode<Integer>都是有效的(满足 AnyType 的界限),但是如果 LinkedList<String> ,您可能会遇到一堆问题正在处理ListNode<Integer> s。

您需要确保任何 ListNode在你的LinkedList里面类全部声明为 ListNode<AnyType> .

旁注,常见的 Java 约定是使用 E而不是AnyType作为集合中通用元素类型的名称。

关于java - 使用泛型时出现类型不兼容错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com