Java - ArrayList does not use formal type parameter for its "elementData" instance field

ArrayList decided to use a reference type Object

in its instance variable elementData

.

Use Object

as a reference type will require explicit casting in obtaining the correct instance type of its elements. What's the difference if it just used a type parameter when declaring the specified instance field?

Thus, I think it might obviate the need to suppress the uncontrolled 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 it be so?

private transient E[] elementData;

public E get(int index) {
    rangeCheck(index);

    return elementData[index];
}

      

Share your thoughts. Hooray!

+3


source to share


2 answers


I already have an answer and it was reading Effective Java 2nd Edition by Joshua Bloch. It says there in paragraph 26.

Which of the two methods you choose to work with the shared array Creation error is largely a matter of taste. All things being equal, it is more risky to suppress an uncontrolled cast to an array type than to a scalar type, which would suggest a second solution. But in a more realistic generic class than Stack, you will probably read from the array at many points in the code, so choosing the second solution would require a lot of casts for E, not a single press on E [], so the first solution is most often used [Naftalin07 , 6.7]



ArrayList uses a second technique when dealing with Generic array creation, which is designed to suppress scalar casting.

+3


source


Due to " type erasure " the type information will be lost anyway. The type information in Java generics exists to help avoid compiler errors when a developer tries to use the wrong type.



However, I believe that the main reason for using Object is that ArrayList also allocates elements. Java doesn't allow doing new E[startCapacity]

. The constructor ArrayList(int initialCapacity)

does exactly that.

+2


source







All Articles