Need an interview question to hire a senior Java developer? How about this one: how many ArrayList classes are there in the JDK? Yes, you heard it correctly: how many classes called ArrayList can you find in the Java Development Toolkit?
Well you know about java.util.ArrayList of course. But did you know there is yet another one? You may actually have used it without knowing it! So the answer is 2: the JDK has 2 ArrayList classes
If you ever used Arrays.asList() to create and initialize a List of objects you created an instance of that second ArrayList class. The fully qualified class name is actually java.util.Arrays$ArrayList.
As you can see from the name it is a nested class defined in the Arrays class. So it is kind of hidden and that’s maybe why you never noticed it before. Let’s quickly compare the two classes.
Comparing ArrayList classes
Let’s quickly compare the two ArrayList classes. They have the same name but what else do they have in common? The table below compares both classes.
- the parent class: both extend AbstractList so not much difference there.
- the interfaces: here things start to differ.
- Small difference Array$ArrayList does not implement the List interface directly. But its parent class AbstractList implements List so that’s not a big deal.
- The only real difference is that Arrays$ArrayList does not implement the Cloneable interface while ArrayList does.
- the methods: as the table shows both ArrayList and Arrays$ArrayList support the common operations of the Collection API: contains(), indexOf(), get(), iterator(),… But that’s were both classes start to differ the most. The Arrays$ArrayList does not support operation which involves reordering elements or resizing the array behind the ArrayList.
- The add() and addAll() methods are not supported since these operations may required the allocation of a new array and copying all the elements to the new array. Something Arrays$ArrayList did not implement. So calling these methods will result in a UnsupportedException being thrown.
- Similarly the remove() and removeAll() were not implemented either. Removing elements from the list implies rearranging the elements in the backing array. This has not been implemented by Arrays$ArrayList instead a UnsupportedException gets thrown
So if you candidate is indeed a seniour Java developer he or she will answer you that there are 2 classes called ArrayList. But that one of them is actually static inner class in java.util.Arrays while the other is the commonly used java.util.ArrayList class.
On the more technical side you could say that while ArrayList is a full fledged List implementation this can not be said for Arrays$ArrayList. The Arrays$ArrayList class is a thin wrapper around an object array which offers a minimal List implementation. The Arrays$ArrayList it pretty much a read-only List.