Common Java methods: super can not be used?

So, I have this method:

protected void collectSelectedItems(ListSelectionModel lsm, Collection<? super MyItemClass> result) { for (int i : GUI.getSelectionIndices(lsm)) { result.add(getItemByDisplayIndex(i)); } } 

I want to return the collection instead of the void method:

 protected <T super MyItemClass> Collection<T> collectSelectedItems(ListSelectionModel lsm, Collection<T> result) { for (int i : GUI.getSelectionIndices(lsm)) { result.add(getItemByDisplayIndex(i)); } return result; } 

with the intention of doing something like this (where MyItemClass extends MyItemBaseClass ):

 List<MyItemBaseClass> list = collectSelectedItems(lsm, new ArrayList<MyItemBaseClass>()); 

but I get a syntax error on super :

Syntax error on super token, expected

What gives? Can i fix this?

+8
java generics bounded-wildcard
source share
3 answers

Here is one link that explains why this is not allowed:

http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ107

Basically, it is simply said that using super in parameters like โ€œdoesnโ€™t buy you anythingโ€, since if it is allowed, erasing will probably just delete it to Object , which does not make much sense.

+6
source share

Here are two ideas. The first returns only the general Collection , the second returns the actual result -type:

 public <T, S extends T> Collection<T> ver1(Collection<S> src, Collection<T> dst) { dst.addAll(src); return dst; } public <U, T extends Collection<U>, S extends U> T ver2(Collection<S> src, T dst) { dst.addAll(src); return dst; } 
+2
source share

well, I definitely did not answer my question, but this is an acceptable solution for my problem:

 protected <T extends Collection<? super MyItemClass>> T collectSelectedItems(ListSelectionModel lsm, T result) { for (int i : GUI.getSelectionIndices(lsm)) { result.add(getItemByDisplayIndex(i)); } return result; } 
0
source share

All Articles