I have a rather simple question. I can’t find an answer by searching though.
Is there a difference in these two code-fragments? And what is the difference?
Fragment1:
public class BinaryTree<T extends Comparable<? super T>> {
...
public <E extends T> void add(E value) {
...
}
public <E extends T> void add(E value, Node node) {
...
}
...
}
Fragment2:
public class BinaryTree<T extends Comparable<? super T>> {
...
public void add(T value) {
...
}
public void add(T value, Node node) {
...
}
...
}
Fragment1 specifies explicitly, that the parameter value must be either of type T or a subtype of type T.
Fragment2 specifies, that the parameter value must be of type T. But from my little knowledge and experience I think that I can also supply a subtype of T here. So same as fragment1.
I looked at the disassembled byte codes of these two fragments. Indeed there is a difference:
< public <E extends T> void add(E);
---
> public void add(T);
That just reflects the source code …
I just don’t get the meaning. And I also can’t find an example application, which shows the difference.
Thanks for comments.
In this case there is no difference. Let’s take for example a
BinaryTree<Number>and try adding anInteger:With fragment 1,
Emay evaluate toInteger, but that’s superfluous in this case.Integeris aNumber, and you could just as well specifyNumberforE:For this reason the second snippet is no different than the first, and less confusing for not declaring an unnecessary type parameter.
There are situations where an additional type parameter would be useful. Imagine for some reason you wanted to return the passed in value:
This would now be useful to the caller:
With the second snippet that wouldn’t be possible, and
numTree.addcould only return aNumbereven if you passed in anInteger.