1
public ArrayList(Collection<? extends E> c) {
       elementData = c.toArray();
       size = elementData.length;

       if (elementData.getClass() != Object[].class)
             elementData = Arrays.copyOf(elementData, size, Object[].class);
}

I did not understand that "if (elementData.getClass() != Object[].class)" statement and why it is required. This is the implementation for ArrayList constructor. Can someone please explain. Thanks!

1 Answer 1

6

Collection.toArray() might return an Object array, or it might return some other array type that has been cast to an Object array. The code you quote is making sure that its data array is actually an Object array, so it is able to receive any Object.

Sign up to request clarification or add additional context in comments.

Comments

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.