gpt4 book ai didi

java - 泛型和 compareTo() 方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:35 25 4
gpt4 key购买 nike

我正在尝试创建一个 SkipList,并且我有一个采用通用数据类型的方法:

public void add(E key, Integer value)
{
Node<E> p;
p = find(key);
}

是什么把你带到了这里:

public Node<E> find(E key)
{
//Start at head
Node<E> p = head;

while (true)
{
while ( (p.getRight().getKey() != Node.posInf) && (p.getRight().getKey().compareTo(key) <= 0 ))
{
p.setRight(p.getRight());
}

//More stuff down here
}
}

问题出在compareTo()上方法。它说 compareTo() E 类型未定义方法.在 Eclipse 中,它希望我像这样添加两个类型转换:

((String) p.getRight().getKey().compareTo((String) key) <= 0 )

为什么要 String ?数据类型可以是任何东西。我尝试对 E 进行类型转换相反,但 Eclipse 想将其改回 String .任何帮助将不胜感激。

最佳答案

你还没有展示如何E已定义,但错误消息表明您没有设置 Comparable<E> 的上限关于E的声明.

你可以在类里面用这样的东西来完成:

public class SkipList<E extends Comparable<E>>

这样您就可以调用 compareTo在你的 key E 类型的变量.

至于为什么 Eclipse 建议转换为 String ,看起来 Eclipse 正在猜测要使其编译的最佳更改是什么。它可能猜到了String因为它是Comparable<String> .在这种情况下,这是错误的,因为 E不一定是 String .这里的解决方案是不同的,正如我上面所说:restrict E成为Comparable<E> .

关于java - 泛型和 compareTo() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275871/

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