Parameterized Methods in a Generic Class

I have a pretty simple question. I can not find the answer, looking though.

Is there a difference in these two code snippets? 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 explicitly indicates that the parameter value must be either of type T or a subtype of type T.

Fragment2 indicates that the parameter value should be of type T. But from my little knowledge and experience, I think I can also provide a subtype of T here. Same as fragment 1.

I looked at the parsed byte codes of these two fragments. Indeed, there is a difference:

<   public <E extends T> void add(E);
---
>   public void add(T);

It just reflects the source code ...

I just don't get the point. And I also can not find an example application that shows the difference.

Thanks for the comments.

+5
source share
2 answers

. , , a BinaryTree<Number> Integer:

BinaryTree<Number> numTree = new BinaryTree<>();
Integer i = 1;
numTree.add(i);

1 E Integer, . Integer - Number, Number E:

numTree.<Number>add(i);

, .


, . , :

public <E extends T> E add(E value) {
   ...
   return value;
}

public <E extends T> E add(E value, Node node) {
   ...
   return value;
}

:

Integer i2 = numTree.add(i);

, , numTree.add Number, Integer.

+4

, add(). Java , , extends <E extends T>.

. T , T. type <E extends T> — , , , , — E.

+1

All Articles