I’m getting a type mismatch error when trying to save a Node into a T variable. From what I understand, Node is a node of a generic type (can be Integer, Animal, whatever) and T is a generic on its own which itself can be Integer, Animal, etc, but is not a node.
How do I use the return of a method that gives Node in a method that wants to return T?
public T get(Object key) {
if (key == null) throw new NullPointerException ("Key cannot be null.");
T result = doGet(root, (int) key);
return (result.data != null ? result.data : null);
}
private Node<T> doGet(Node<T> r, int k) { ...
I’ve tried casting, but I just get an unchecked cast from Node to T warning.
>Solution :
The doGet(root, (int) key) method is an expression of type Node<T>, so, fix your code to reflect this:
Node<T> result = doGet(root, (int) key);
And, clearly, result.data is of type T. So, other than that fix, all works great.
Note that casting Object key to int smells of bad code. Your API indicates key can be any object, but, actually, it must be an Integer, or that cast will fail. So why isn’t the type of the get method Integer key then, or int key?