Cloning a Collection

The Collection Java interface, root of all the standard Java collections does not support cloning. If we are working with a collection without knowing its actual type, we can bypass this issue converting it to an array.

If we really want to create a shallow copy of our collection we have to engage ourselves in writing a piece of kind of dirty code involving a safe downcast to the actual type of our collection and then an upcast back to the Collection interface.

As example, let's create an ArrayList of Integers and add a few items to it:
Collection c = new ArrayList(3); // 1
c.add(1); // 2
c.add(2);
c.add(3);
1. Following the good practice of working with abstractions whenever it is possible, we create an ArrayList, specifying Integer as underlying type and then we assign its address in memory to a Collection interface. I have even specified the number of expected elements, so that the ArrayList is created of the right size, avoiding memory waste or the need of (automatically) resize the collection.
2. An int is passed to add(), thanks to autoboxing, it is automatically boxed in the relative wrapper type.

A Collection object can't be cloned, so let's downcast it:
if(c instanceof ArrayList) { // 1
    Collection c2 = ((Collection)((ArrayList)c).clone()); // 2
    // ...
}
1. Better playing safely, before downcasting we explicitly check the actual collection type, in this way we don't have to try/catch this code for always possible bad casting.
2. Here we know that the actual type of our collection is indeed an ArrayList, so we downcast it and call the ArrayList.clone() function. Still we usually want to going on working with a Collection interface.

No comments:

Post a Comment