How to initialize a dynamic array in java?

lock picture lock · Sep 7, 2010 · Viewed 26k times · Source

If I have a class that needs to return an array of strings of variable dimension (and that dimension could only be determined upon running some method of the class), how do I declare the dynamic array in my class' constructor?

If the question wasn't clear enough,

in php we could simply declare an array of strings as $my_string_array = array(); and add elements to it by $my_string_array[] = "New value";

What is the above code equivalent then in java?

Answer

Tom Neyland picture Tom Neyland · Sep 7, 2010

You will want to look into the java.util package, specifically the ArrayList class. It has methods such as .add() .remove() .indexof() .contains() .toArray(), and more.