6

I am trying to make a SkipList and I have a method that takes a generic data type:

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

Which takes you here:

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
    }
}

The problem is on the compareTo() method. It says the compareTo() method is undefined for type E. In Eclipse it wants me to add two typecasts like this:

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

Why does it want String? The data type could be anything. I tried doing typecast of E instead but Eclipse wants to change it back to String. Any help would be appreciated.

4

2 回答 2

8

您尚未显示如何E定义,但错误消息表明您没有Comparable<E>E.

您可以在课堂上通过以下方式完成此操作:

public class SkipList<E extends Comparable<E>>

这将允许您调用compareTokey的类型变量E

至于为什么 Eclipse 建议转换为String. 它可能已经猜到String了,因为它是Comparable<String>. 在这种情况下,这是错误的,因为E不一定是String. 正如我上面所说,这里的解决方案是不同的:restrict Eto be Comparable<E>

于 2015-07-07T17:54:46.430 回答
5

该方法compareTo在接口中定义java.lang.Comparable。您的代码中没有任何内容告诉编译器类型参数EComparable. 您可以在泛型类型声明中执行此操作:

class Node<E extends Comparable<E>> {
   ...
}

默认情况下,如果不声明extends Comparable,则只能访问java.lang.Object类中定义的方法。

于 2015-07-07T17:54:35.140 回答