Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing type parameters in Java inner class

Tags:

java

generics

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?

like image 680
ion20 Avatar asked Aug 29 '15 21:08

ion20


1 Answers

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.

like image 123
adelphus Avatar answered Sep 24 '22 04:09

adelphus