Java – generics and CompareTo () methods
I'm trying to create a skiplist. I have a method using common data types:
public void add(E key,Integer value) { Node<E> p; p = find(key); }
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 with the CompareTo () method It says that the CompareTo () method of type E is undefined In eclipse, it asks me to add two such type conversions:
((String)p.getRight(). getKey(). CompareTo ((string) key) < = 0) why string? The data type can be anything I tried to type E, but eclipse wanted to change it back to string Any help will be greatly appreciated
Solution
You have not shown how e is defined, but the error message indicates that you have not placed the upper limit of comparable < E > Statement on e
You can do it in class with something like this:
public class SkipList<E extends Comparable<E>>
This will allow you to call CompareTo. On a key variable of type E
As for why eclipse recommends converting to string, it seems that eclipse is guessing what the best change is to compile it It may have guessed string because it is comparable < string > In this case, it is wrong because e is not necessarily string The solution here is different, as described above: limit e to comparable < E >