Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between using generic T vs Node<T>?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading