Possible Duplicate:
How do you cast a List of objects from one type to another in Java?
Searched the internet a little, and found no nice way of doing it… My solution now is:
public class A {}
List<Object> obj = new ArrayList<Object>();
obj.add(new A());
// Ugly solution here:
List<A> a = (List<A>) (List) obj;
But this is quite ugly and gets a warning. No “official” way of doing this?
EDIT: To the guys who closed this: I was aware of the solution posted in How do you cast a List of objects from one type to another in Java? It is the same as the one I posted in my question (just adding the <?> after the first cast does exactly the same) I Was looking for something more “clean”. In the direction of using the Class<?> clazz = listobj.get(0).getClass way of getting the class and casting to the correct class at runtime (but no idea if something like that works… Eclipse doesn’t seem to like it anyway…)
It is not the right way to write code. Basically you are creating a generic List and adding Object to it and it type unsafe and keep any Object type.
It is recommended to create type-safe
ListlikeList<A> obj = new ArrayList<A>();you can do this in such a way –