ArrayList chose to just use a reference type of Object in its instance variable elementData.
Using Object as its reference type would require explicit cast in getting the correct instance type of its elements. What's the difference if it just used type parameter in declaring said instance field?
By that, I think it could eliminate the need for suppressing unchecked explicit cast.
// From Java API:
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
could have been like this?
private transient E[] elementData;
public E get(int index) {
rangeCheck(index);
return elementData[index];
}
Please share your thoughts. Cheers!
I've already got the answer and it's from reading "Effective Java 2nd Edition" by Joshua Bloch. It says there in Item 26..
Which of the two techniques you choose for dealing with the generic array creation error is largely a matter of taste. All other things being equal, it is riskier to suppress an unchecked cast to an array type than to a scalar type, which would suggest the second solution. But in a more realistic generic class than Stack, you would probably be reading from the array at many points in the code, so choosing the second solution would require many casts to E rather than a single cast to E[], which is why the first solution is usedmore commonly [Naftalin07, 6.7]
ArrayList is using the second technique in dealing with Generic array creation which is to suppress cast to a scalar type.
Due to the "type erasure" the type information will be lost anyway. The type information in Java generics is there to help compiler issue errors when developer is trying to use incorrect type.
However, I believe the main reason to use Object there is that ArrayList is allocating elements as well. Java does not allow you to do new E[startCapacity]. ArrayList(int initialCapacity) constructor is doing exactly that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With