I would like to write a method that would return a java.util.List
of any type without the need to typecast anything:
List<User> users = magicalListGetter(User.class);
List<Vehicle> vehicles = magicalListGetter(Vehicle.class);
List<String> strings = magicalListGetter(String.class);
What would the method signature look like? Something like this, perhaps(?):
public List<<?> ?> magicalListGetter(Class<?> clazz) {
List<?> list = doMagicalVooDooHere();
return list;
}
Thanks in advance!
I'm pretty sure you can completely delete the <stuff> , which will generate a warning and you can use an, @ suppress warnings. If you really want it to be generic, but to use any of its elements you will have to do type casting. For instance, I made a simple bubble sort function and it uses a generic type when sorting the list, which is actually an array of Comparable in this case. If you wish to use an item, do something like: System.out.println((Double)arrayOfDoubles[0] + (Double)arrayOfDoubles[1]); because I stuffed Double(s) into Comparable(s) which is polymorphism since all Double(s) inherit from Comparable to allow easy sorting through Collections.sort()
One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (
klazz.getConstructor().newInstance()
).Something like this
You can simply cast to List and then check if every element can be casted to T.
No need to even pass the class:
You can use the old way:
or you can use
Object
and the parent class of everything:Note Perhaps there is a better parent class for all the objects you will put in the list. For example,
Number
would allow you to putDouble
andInteger
in there.