Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic methods: super can't 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'd like to return the collection instead of having a 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 intent of doing something like this (where MyItemClass extends MyItemBaseClass):

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

but I get a syntax error on the super:

Syntax error on token "super", , expected

What gives? Can I fix this?

like image 420
Jason S Avatar asked Dec 06 '11 16:12

Jason S


People also ask

What are not allowed for generics?

Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types. Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types.

What does <? Super t mean in Java?

super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .

What is Java generics in what scenarios we can and Cannot use generics?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

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

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

It basically just says that use super in type parameters "does not buy you anything", since if this is allowed, erasure will probably just erase it to Object, which does not make much sense.

like image 147
zw324 Avatar answered Sep 17 '22 09:09

zw324