Java - Casting in E []

When I apply to E[] (class parameter), I need to add

 @SuppressWarnings("unchecked") 

For instance:

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

Should I do something else, or should it be like that?

thanks

+4
source share
4 answers

It is right. 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. 

How this works, you must explicitly indicate that the compiler ignores this feature.

+4
source

You should probably read Effective Java . In short, it is impossible to say exactly what the right course of action is for you, because we do not know what you are doing, but in general you should not suppress this warning. Thus, most likely, the solution for you is to use typical general collections instead of arrays.

+3
source

This was supposed to be due to the type of erasure .

To avoid having to suppress this warning, the only thing you can do is use List<E> (or a similar Collection ).

+2
source

Yes, you should do it this way, because we cannot initialize arrays of generics such as this:

 E[] array = new E[10]; // Compile error 

You really need to do this, as you wrote. I donโ€™t know about that.


Another approach is to use an array of objects (instead of E). You can see that the Java API developers did this the same way as in the ArrayList class:

 /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */ private transient Object[] elementData; 

And they just initialize this array as follows:

 elementData = new Object[size]; 

And wherever they are used, they highlight the contents of the array:

 /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { RangeCheck(index); return (E) elementData[index]; } 

I am not sure, but I believe that the first approach is faster because casting is not required during the execution process. I think the Java VM will spend some time on this. Why do I think so? Since this gives a runtime error:

 Integer i = new Integer(34); Object o = i; String s = (String) o; // Runtime error 

So this means that the virtual machine really checked if it is string. But the fact that the compiler does the erasing of styles makes me think that it doesn't make any difference. Can someone clarify?

+2
source

Source: https://habr.com/ru/post/1392560/


All Articles