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 = a开发者_高级运维rray();
and add elements to it by $my_string_array[] = "New value";
What is the above code equivalent then in java?
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.
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 synchronizedVector
- synchronized, array based implementationLinkedList
- 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.
Create a List
instead.
List<String> l = new LinkedList<String>();
l.add("foo");
l.add("bar");
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 :)
精彩评论