13

What is the difference between doing

public class BST<Key extends Comparable<Key>, Value> {

    public class Node<Key, Value> {
       Key key;
       Value val;
    }
}

and doing

public class BST<Key extends Comparable<Key>, Value> {

    public class Node {
       Key key;
       Value val;
    }
}

i.e. do the type parameters on the inner class matter? Which implementation is better?

1

1 Answer 1

13

You seem to think the two are equivalent - they are not. The top example declares two generic classes, the bottom example declares one generic class and one non-generic inner class.

For example, in the top declaration you could create an instance like this...

BST<MyComparable, String>.Node<Integer, Boolean> x = new ...

...because the type parameters are distinct between the two classes - you've just chosen to give the inner generic type parameters the same name as the type parameters in the outer class, but they are not related.

If you try to do that in the second example, you'll get an error because the inner class Node is not generic. In the second example, the types of the Node fields must match the outer type parameters.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, so in the first implementation, Key/Value on the inner class are not the same as Key/Value on the outer class? Also, is it safe to say that if I want to enforce that my inner class uses the same type parameters that my outer class is using, I shouldn't make the inner class generic (like my first implementation)?
Exactly. The inner class could be made generic if you need it to, but if you require it to use the types from the outer class, you cannot reuse the type names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.