Java: Difference Between Arrays and ArrayLists
This is part of the Interview Guide Series I’ve been putting together as I prepare for my next round of interviews.
This is a question that has been posed to me in multiple interviews, so I’ve decided to sit down and attempt to enumerate the differences in an effort to create a solid answer. I’ve compiled my answer from a mix of Java Docs and other posts attempting to do the same thing. You can find a link to them in the Reference section.
“Arrays are container objects that can hold a fixed number of values of a single type” (Arrays). You’ve probably seen them used to hold several ints or chars before. The important thing to remember here is that arrays hold a fixed number of values.
ArrayLists are a data structure that implements the collection framework. It also uses an array to store the actual data, but provides built-in functions to add, delete, update, resize, and otherwise manage the data structure without actually touching it. This layer of abstraction makes it easier on the user to carry out functions as they don’t have to worry about what’s going on behind the scenes. The resize feature is key here as it automatically resizes the underlying array based on capacity and load factor, allowing you to continue adding elements, to some degree, without worrying about having to resize the underlying array yourself.
A full list of built-in functions provided by ArrayLists can be found in the ArrayList JavaDocs.
- Arrays are a fixed-length data structure while ArrayLists dynamically resize.
- You can’t use generics in Arrays, but can in ArrayLists. This also means that you can store elements of different types inside an ArrayList while you can’t inside an array.
- ArrayLists cannot hold primitives. Any primitive types passed in must be converted to an associated Object type. Arrays can hold both primitives and Objects.
ArrayList – Java Docs – http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Arrays – Java Docs – http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Difference Between Array vs ArrayList in Java – http://java67.blogspot.com/2012/12/difference-between-array-vs-arraylist-java.html