How can I make a resizable array in Java?

Soren Johnson picture Soren Johnson · Apr 6, 2010 · Viewed 22.9k times · Source

What is the best way to do a resizable array in Java? I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place. I'm sure there's a simple answer for this, but I still not quite sure.

Answer

Kevin Crowell picture Kevin Crowell · Apr 6, 2010

As an alternative, you could use an ArrayList. It is a resizable-array implementation of the List interface.

Usage (using String):

List<String> myList = new ArrayList<String>();
myList.add("a");
myList.add("c");
myList.add("b");

The order will be just like you put them in: a, c, b.

You can also get an individual item like this:

String myString = myList.get(0);

Which will give you the 0th element: "a".