8
  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.

1 Answer 1

12

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[]
Sign up to request clarification or add additional context in comments.

1 Comment

That's wrong. Tested with java 8 and it runs without any error/Exception. And if you print the list, it gets printed as well without any problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.