Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 http://bugs.sun.com/bugdatabase/view_bug.do?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.

like image 823
ChandlerSong Avatar asked Dec 15 '11 13:12

ChandlerSong


People also ask

Can we convert array to ArrayList in Java?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

How do you create an ArrayList of objects?

Using the add() method to create ArrayList of objects in java. You can simply use add() method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.

Is ArrayList parameterized?

But ArrayList is a parameterized type. A parameterized type can take a type parameter, so that from the single class ArrayList, we get a multitude of types including ArrayList<String>, ArrayList<Color>, and in fact ArrayList<T> for any object type T.


1 Answers

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[]
like image 179
axtavt Avatar answered Oct 19 '22 15:10

axtavt