views:

75

answers:

4

I have this code:

newArray = new String[][]{{"Me","123"},{"You","321"},{"He","221"}};

And I want to do this dynamically. Add more elements, things like it.

How do I do this?

PS: Without using Vector, just using String[][];

+8  A: 

You can't change the size of an array. You have to create a new array and copy all content from the old array to the new array.

That's why it's much easier to use the java collection classes like ArrayList, HashSet, ...

tangens
A: 

You can't change the size of arrays. I think you have some options:

  1. use a List<List<String>> to store a list of lists of strings
  2. use a Map<String,String> if you're storing a key/value pair

Vector tends not to be used these days, btw. A Vector is synchronised on each method call, and thus there's a performance hit (negligible nowadays with modern VMs)

Brian Agnew
A: 

Java does not have the facility to resize arrays like some other languages.

But
You would not see a difference between a String array and a ArrayList<String> (javadoc) unless you are specifically required to do so (like in homework)

There are ways where you can declare a enormous array so that you dont run out of space but I would strongly recommend ArrayList for if you need dynamic changes to the size. And ArrayList provides some possibilities that are not (directly) possible with an array, as a bonus.

Nivas
A: 

You can get away with using arrays if it's possible to calculate the size of arrays before using them. In your example, it seems that we need to know the size of the first array only. So you could impose some limit of how many records could be saved, or you could query user to know how many records it needs to save or something similar.

But again, it's easier to use Collections.

Tumas