Reputation: 959
I created list using method Arrays.asList()
with one String.
Then I assigned it to List<Object>
, and I get ClassCastException.
What did I do wrong?
The code is:
class A {
Object value;
public <T> T getAValue() {
return (T) value;
}
}
And then I do
A a = new A();
a.value = "abc";
List<Object> list = Arrays.asList(a.getAValue());
Upvotes: 0
Views: 71
Reputation:
If you really cannot add type info on A
(i.e. use class A<T>
), then a simple cast solves your issue, like this (demo):
A a = new A();
a.value = "abc";
List<Object> list = Arrays.asList((Object) a.getAValue());
This is safe, because everything is an Object
, but the clean way is to use type info on A
, as stated in another answer (demo):
A<String> a = new A<String>();
a.value = "abc";
List<String> list = Arrays.asList(a.getAValue());
Also note that you should use a setter for value
(i.e. no a.value = "..."
).
Some reading: https://docs.oracle.com/javase/tutorial/java/generics/
Upvotes: 1
Reputation: 7867
Try this:
import java.util.Arrays;
import java.util.List;
class A<T>{
T value;
public T getAValue(){
return value;
}
public static void main(String... args){
A a = new A();
a.value = "abc";
List<Object> list = Arrays.asList(a.getAValue());
System.out.println(list);
System.out.println(a.value.getClass());
}
}
Note the simplified syntax by declaring the generic type 'T' when declaring class A<T>
T's type is bound to String and it is unnecessary to cast the return value in the getAValue(), generics take care of that for you.
Upvotes: 1