'[Ljava.lang.Object; cannot be cast to [Ljava.lang.String; when I use generic
When I run code below:
public class GenericTest<T> {
private T[] arr = (T[]) new Object[5];//泛型不能直接创建,但是可以这样转型
public static void func(GenericTest<String> gt){
for(int i = 0; i < gt.arr.length; i++){
if(gt.arr[i] == null)
System.out.print(i);
}
}
public static void main(String[] args){
GenericTest<String> gt = new GenericTest<>();
//gt.func();
func(gt);
}
}
I got a error:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.String; [duplicate]
But when I run code like this (though they like very similar):
public class GenericTest<T> {
private T[] arr = (T[]) new Object[5];//泛型不能直接创建,但是可以这样转型
public void func(){
for(int i = 0; i < arr.length; i++){
if(arr[i] == null)
System.out.print(i);
}
}
public static void main(String[] args){
GenericTest<String> gt = new GenericTest<>();
gt.func();
//func(gt);
}
}
I can get what I want to see:
01234
Process finished with exit code 0
Solution 1:[1]
Well, they may look similar, but they are not.
The thing is that with func(), the compiler knows nothing about the actual generic type of GenericTest, except that is is eventually an Object. Retrieving arr.length will just work fine.
But then look at void func(GenericTest<String> gt). The argument mandates that a GenericTest<String> is passed in. So the compiler inserts a type cast for arr to a String[]:
((String[]) gt.arr).length
And guess what – gt.arr is actually an Object[], which can, of course, not be converted to a String[].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MC Emperor |
