Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Casting to E[]

Tags:

java

casting

When I cast to E[] (the class parameter), it requires me to add

@SuppressWarnings("unchecked")

For example:

E[] anArray = (E[]) new Object[10];

Should I be doing something different, or is it supposed to be like this?

Thanks

like image 269
Stripies Avatar asked Dec 27 '22 07:12

Stripies


1 Answers

It is correct. Imagine:

Object[] o = new Object[10];
o[0] = new A(); // A is not a subclass of E
E[] e = o; // Now you have broken the type system: e[0] references something that is not an E.

The way it works, you have to explicitly cast in order to make the compiler ignore this possibility.

like image 125
gpeche Avatar answered Jan 09 '23 05:01

gpeche