Variable length (Dynamic) Arrays in Java

Mohammad Sepahvand picture Mohammad Sepahvand · Mar 11, 2010 · Viewed 430.2k times · Source

I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions?

Answer

Pops picture Pops · Mar 11, 2010

Yes: use ArrayList.

In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.

Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.

One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.