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 first n
positions.
Fortunately, there are java.util.List
implementations that do this work for you. Both java.util.ArrayList
and java.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 synchronized
Vector
- synchronized, array based implementation
LinkedList
- Doubly linked list implementation, faster for inserting items in the middle of a list
Do 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 is java.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 a Map<String, String>
, also in the java.util
package. A good general-purpose map implementation is HashMap
.
Once you've created your map,
- Use
map.put("key", "string")
to add strings
- Use
map.get("key")
to access a string by its key.
Note that java.util.Map
cannot contain duplicate keys. If you call put
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.