That doesn't work, because the inside of the method does't really know what T
is (because Java generics work by type erasure). Instead, you should either:
- Rely on the generics system to enforce things for you and stop trying to check them, or
- Pass in the explicit class that you're searching for. (This would also help if you were looking for a
Cat
class and T
was Animal
, assuming that Cat
is a subtype of Animal
.)
public <T> ArrayList<T> getAllItems(Class<T> clazz) {
for (ArrayList<?> itemList : wardrobe) {
Iterator<?> iterator = itemList.iterator();
if(iterator.hasNext()){
Object next = iterator.next();
if(clazz.isAssignableFrom(next.getClass()))
return (ArrayList<T>)itemList;
}
}
return null;
}
You'll need to suppress some warnings here, as the cast is formally unsafe, but it will be OK provided each list in wardrobe
really is of a single type of element (or at least that they don't have a shared superclass).