Hi all i am learning Generics in Java. in which i have created this hierarchy.
Now i have created a LivingThing
class
public class LivingThing<T extends LivingThingTypes> implements Iterable<LivingThingTypes>{
public ArrayList<T> create(Class<T> type) {
ArrayList arrayList = new ArrayList<>();
for (T item : list) {
if (item.getClass().equals(type)) {
arrayList.add(item);
}
}
return arrayList;
}
}
So when i try to access create()
method like this code of section it doesn't works.
livingList.create(Human.class).size();
livingList.create(Cat.class).size();
livingList.create(Hen.class).size();
But if i change method into this it works perfectly
public class LivingThing<T extends LivingThingTypes> implements Iterable<LivingThingTypes>{
public <V extends LivingThingTypes>ArrayList<V> create(Class<V> type) {
ArrayList arrayList = new ArrayList<>();
for (T item : list) {
if (item.getClass().equals(type)) {
arrayList.add(item);
}
}
return arrayList;
}
}