Is creating an array and creating an arraylist the same thing in Java? I hear many different stories with regard to this so if you could point me into the right direction it would much appreciated :)
4 Answers
An array is a primitive structure. It is sequential memory and allocated by the JVM.
An arraylist uses an array behind it, but you don't have direct access to it. It can "grow" while a regular array cannot.
Basically, an arraylist starts (by default) with an array of length 10 behind it, and a count of 0. So imagine you had
ArrayList<Integer> myInts = new ArrayList<Integer>();
behind this is an array like this
count = 0
array = [ null, null, null, null, null, null, null, null, null, null ]
When you go myInts.add(5); it does this
count = 1
array = [ 5, null, null, null, null, null, null, null, null, null ]
If you added more you could get this
count = 10
array = [ 5, 4, 3, 2, 1, 5, 8, 3, 0, -1 ]
And if you added one more (which would push it beyond its capacity) it would make a new array to support it
count = 11
array = [ 5, 4, 3, 2, 1, 5, 8, 3, 0, -1, 9, null, null, null, null, null, null, null, null, null ]
You can change the size of the backing array if you want to. for example:
myInts.trimToSize();
count = 11 // hasn't changed
array = [ 5, 4, 3, 2, 1, 5, 8, 3, 0, -1, 9]
myInts.ensureCapacity(15);
count = 11 // hasn't changed
array = [ 5, 4, 3, 2, 1, 5, 8, 3, 0, -1, 9, null, null, null, null,]
Comments
You can have an array of primitive types while ArrayList doesn't support the primitive types.
You can save some memory if you use Array instead of ArrayList, but will not have the extra features provided by the Java Collection Framework.
4 Comments
No, these are not the same thing.
Support for real arrays is part of the Java language and the Java Virtual Machine. There are specific instructions in the JVM instruction set to work with arrays.
An ArrayList is just a class that's part of the core Java libraries. Internally, it stores elements in a Java array. Compare it to other list implementations like LinkedList.
In practice, a List implementation like ArrayList offers more features than an array. For example, an ArrayList can have a varying size, and will re-allocate the underlying array if more space is needed.