What Is the Difference Between Arrays and ArrayLists in Java

This will not be an exhaustive answer. To understand the full details, you’ll need to look at the Java documentation provided by Sun Microsystems.

An array in Java is immutable, which means that when you create it, it is stored in a specific place in memory and never moved until it is no longer needed and gets picked up by the garbage collector. You can’t add or remove items from arrays without recreating new ones–its size is fixed from the time you instantiate it (which is why you have to specify how large it is at that time). Arrays have been used for a long time in programming. You instantiate it in a way such as the following:

String[] array = new String[] {"abc", "def", "ghi"};

An ArrayList is a Collection class and is basically a mutable version of an array. When you instantiate one of these, a small amount of memory is set aside for it. The nice thing is that you can add and remove items from it on the fly. As you do so, more (or less) memory (not necessarily contiguous with the original memory) will be acquired (or released) so it can store what it needs to at the time. This can be very convenient, but it can also require more CPU and memory resources if you make a lot of modifications to it. You can create an ArrayList object similar to the above array like this:

ArrayList list = new ArrayList();
list.add("abc");
list.add("def");
list.add("ghi");

One Response to “What Is the Difference Between Arrays and ArrayLists in Java”

  1. Great post!

    I’ve worked mainly in PHP where Arrays are mutable by default, and switching now to Java it’s a different world. This really helped a lot and saved me about twenty minutes of java doc reading!

Leave a Reply