Domanda

lets say I've a wardrobe i can put list, list,..

ArrayList<ArrayList<?>> wardrobe

Then i want to list items of specific type.

if i say list all my shirts,

i thought of

public <T> ArrayList<?> getAllItems() {
    for (ArrayList<?> itemList : wardrobe) {
        Iterator<?> iterator = itemList.iterator();
        if(iterator.hasNext()){
            Object next = iterator.next();
            if(next.getClass().equals(T)) return itemList;
        }
    }
    return null;
}
  1. but its an error! am i missing anything (misunderstood the generics concept?)!
  2. How can i achieve that?

i thought of calling

<Shirt>getAllItems();
È stato utile?

Soluzione

Change your method definition like this

public <T> ArrayList<?> getAllItems(Class<T> clazz) {
    for (ArrayList<?> itemList : wardrobe) {
        Iterator<?> iterator = itemList.iterator();
        if(iterator.hasNext()){
            Object next = iterator.next();
            if(next.getClass().equals(clazz)) return itemList;
        }
    }
    return null;
}

then, call <Shirt> getAllItems(Shirt.class);

Hope this helps!

Altri suggerimenti

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top