Yes, you should do it this way, because we cannot initialize arrays of generics such as this:
E[] array = new E[10];
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:
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:
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;
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?
source share