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.
No, there is no difference between the two variations of the
add()
method. Java's method arguments already establish an upper bound on the accepted type, which is the same constraint accomplished by using theextends
form of your type variable<E extends T>
.Your type variable adds no new information nor does it add any additional constraints. It was already legal to pass an argument of type
T
or any type that extendsT
. Your type variable<E extends T>
does provide a way to refer to the actual argument type again—say, if there was a second method parameter that you wanted to ensure was of the same type as the first—but in your case, you're not making use ofE
.In this case there is no difference. Let's take for example a
BinaryTree<Number>
and try adding anInteger
:With fragment 1,
E
may evaluate toInteger
, but that's superfluous in this case.Integer
is aNumber
, and you could just as well specifyNumber
forE
: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.add
could only return aNumber
even if you passed in anInteger
.