How to get a sub-collection of a passed collection<generic type> where members extend or implement another?

StackOverflow https://stackoverflow.com/questions/18951672

Question

Part of something I'm doing involves a function with two generic type arguments (T1, T2), and an argument, which is a Collection. I need to get a sub-collection or sub-list of the Collection containing all members of the collection that implement or inherit from/extend T2.

My original idea was to do it the way that, to me, seemed obvious, which would have been:

<T1, T2> void someMethod(Collection<T1> collection)
{
    List<T2> sublist = new ArrayList<T2>();

    for(T1 i : collection)
        if(i instanceof T2)
            sublist.add((T2)i);
}

But instanceof can't be used on Generic types in Java.

Thanks for any help ^_^

Était-ce utile?

La solution

The only way to do this instanceof check is to pass the Class object representing the type:

<T1, T2> void someMethod(Collection<T1> collection, Class<T2> type) {
        List<T2> sublist = new ArrayList<T2>();

        for (T1 i : collection) {
            if (type.isAssignableFrom(i.getClass())) {
                sublist.add((T2) i);
            }
        }


    }

Autres conseils

Assuming T1 is down below the type hierarchy from T2, then you can declare your method like this:

  <T2, T1 extends T2> void someMethod(Collection<T1> collection)
  {
      List<T2> sublist = new ArrayList<T2>();

      for(T1 i : collection)
              sublist.add(i);
  }

Note you don't event need to runtime-check i because if T1 isn't chained to the type hierarchy below T2 anywhere the compiler will throw compile-time error

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top