Potatoman Potatoman - 28 days ago 11
Java Question

JAVA Why do I get a type error when assigning these variables (T extends Comparable<T>)

So, let's say we have these two classes.

public class Main<T extends Comparable<T>> {
public List<T> toList(T t){
Node n = new Node();
n.value = t; //This assignment1 gives no issues.

List<T> list = new List<T>();
list.add(n.value); //This assignment2 gives a type error.
return list;
}
}

class Node <T extends Comparable<T>> {
T value = null;
}


So, why does assignment1 go through without a type error, while assignment2 gives me the following error:

add (T) in List cannot be applied to (java.lang.Comparable)

It disappears when I do:

list.add((T)n.value);


But I would like to understand the reason first to figure out if above solution is the correct one.

EDIT: For now, I should specify that the code that uses these classes are Integer objects. So, I as the developer can assume that the T types are the same. But I am not sure if the code has some underlying routine that can change the values during casting.

Answer
Node n = new Node();

should be

Node<T> n = new Node<T>();

If you ever refer to Node without <something> after it, you are telling the compiler to ignore all type checking on Node. This will give you warnings, as it should.

Comments