Generics Method and compareTo ()

I am trying to create a SkipList, and I have a method that uses a common data type:

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

Which will bring 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 the compareTo() method. He says the compareTo() method is undefined for type E In Eclipse, he wants me to add two such models:

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

Why does he want String ? The data type can be any. I tried to make typecast E instead, but Eclipse wants to change it to String . Any help would be appreciated.

+6
source share
2 answers

You did not specify how E is defined, but the error message indicates that you did not specify the upper bound of Comparable<E> in the declaration of E

You can do this with something like this in your class:

 public class SkipList<E extends Comparable<E>> 

This will allow you to call compareTo on your key variable of type E

As to why Eclipse offers casting for String , it looks like Eclipse is guessing what would be the best change to make it compile. Perhaps he suggested String because it is Comparable<String> . In this case, this is wrong, because E not necessarily a String . The solution here is different, as I said above: restrict E Comparable<E> .

+7
source

The compareTo method is defined in the java.lang.Comparable interface. There is nothing in the code that tells the compiler that a parameter of type E is Comparable . You can do this in a generic declaration:

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

By default, if you do not declare extends Comparable , you can only access the methods defined in the java.lang.Object class.

+5
source

All Articles