Reputation: 5217
I have to following problem: I have a generic class called Generic<A>
and some instances of this class lets say
Generic<String> foo;
Generic<Double> bar;
and i put them into a list like this:
List<Generic<?>> list;
list.add(foo);
list.add(bar);
now i want to read a method that returns A
, but instead i only get Object
as return type, and i know why, because of the ? in the generic type of the list. I also know that List<Generic<String>>
is a complete different type than List<Generic<Double>>
... But is there any kind of List Structure or Generic Type argument that i can use to keep the Type of the Generic class the same? Its no problem to cast for me in my program, because i save also a ID for every Instance in my list and now can determinate which type is in there but this seems a little bit dirty...
Upvotes: 1
Views: 101
Reputation: 3289
Do you have to use the ?
or can you change your code to use List<Generic<T>>
to keep the type?
If you want to check the type after initialising the List
with some content, you can use list.get(0).getClass()
to gain some information but that's not really a nice way to program
Upvotes: 0
Reputation: 28168
Is it this what you are looking for?:
public <T> T someMethod(List<Generic<T>> list){
//Return an element from list
}
Upvotes: 1
Reputation: 6543
Well if you whant a common type you should use Object or some class that wrapps your stuff. If you use Object then just check instanceof the object in your method where you do stuff
Upvotes: 0