I recently tried to create an array of generics and found out it is not allowed:
Cannot create generic array of OptionSet<T>
I decided to make a test class and found out that there is a different method with exactly the same result that does work:
public class Test {
@SuppressWarnings("unchecked")
public static final void main(String[] args) {
A<String> a = null;
A<String> b = null;
A<?>[] array1 = array(a, b); // fine, only a warning
A<?>[] array2 = new A<String>[] {a, b}; // Error: Cannot create a generic array of Test.A<String>
}
@SuppressWarnings("unchecked")
private static final <T> A<T>[] array(A<T>... a) {
return a; // fine, only a warning
}
private static final class A<T> {}
}
Why is that? Both methods have exactly the same result, but for some reason one throws an error and the other works fine, although it gives a warning.
It's because of casting is happening in case of method call via return type private static final <T> A<T>[] array(A<T>... a)
which is not in case of A<?>[] array2 = new A<String>[] {a, b};
where you're directly creating the instance.
to make it work You need to cast explicitly like below:
A<?>[] array2 = (A<String>[])(new A<?>[] { a, b });
What's happening is the elements are A<String>
but not the array itself; it's still generic A<?>
until you cast it explicitly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.