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?
Create a
List
instead.No dynamic array in java, length of array is fixed. Similar structure is
ArrayList
, a real array is implemented underlying it. See the name ArrayList :)Plain java arrays (ie
String[] strings
) cannot be resized dynamically; when you're out of room but you still want to add elements to your array, you need to create a bigger one and copy the existing array into its firstn
positions.Fortunately, there are
java.util.List
implementations that do this work for you. Bothjava.util.ArrayList
andjava.util.Vector
are implemented using arrays.But then, do you really care if the strings happen to be stored internally in an array, or do you just need a collection that will let you keep adding items without worrying about running out of room? If the latter, then you can pick any of the several general purpose
List
implementations out there. Most of the time the choices are:ArrayList
- basic array based implementation, not synchronizedVector
- synchronized, array based implementationLinkedList
- Doubly linked list implementation, faster for inserting items in the middle of a listDo you expect your list to have duplicate items? If duplicate items should never exist for your use case, then you should prefer a
java.util.Set
. Sets are guaranteed to not contain duplicate items. A good general-purpose set implementation isjava.util.HashSet
.Answer to follow-up question
To access strings using an index similar to
$my_string_array["property"]
, you need to put them in aMap<String, String>
, also in thejava.util
package. A good general-purpose map implementation isHashMap
.Once you've created your map,
map.put("key", "string")
to add stringsmap.get("key")
to access a string by its key.Note that
java.util.Map
cannot contain duplicate keys. If you callput
consecutively with the same key, only the value set in the latest call will remain, the earlier ones will be lost. But I'd guess this is also the behavior for PHP associative arrays, so it shouldn't be a surprise.You will want to look into the
java.util package
, specifically theArrayList
class. It has methods such as.add() .remove() .indexof() .contains() .toArray()
, and more.