ChandlerSong
ChandlerSong

Reputation: 487

why need to convert type to Object array in ArrayList's Construction?

  public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
    elementData = Arrays.copyOf(elementData, size, Object[].class);
}

the code is the construction of java.util.ArrayList. you can check the details of bug 6260652, here https://bugs.java.com/bugdatabase/view_bug?bug_id=6260652

my question is if I don't convert the type, what problem will happen? Because I think it's totally OK if elementData refer to subType array.

Upvotes: 8

Views: 1239

Answers (1)

axtavt
axtavt

Reputation: 242686

Here is an example of what may go wrong without the conversion in question:

List<Object> l = new ArrayList<Object>(Arrays.asList("foo", "bar"));

// Arrays.asList("foo", "bar").toArray() produces String[], 
// and l is backed by that array

l.set(0, new Object()); // Causes ArrayStoreException, because you cannot put
                        // arbitrary Object into String[]

Upvotes: 12

Related Questions