0

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[][];

2
  • It seems to me that the person who posted this must have started out programming with a language that had built in dynamic arrays like python. Tangens answer is perfect. There are many many collection types that allow dynamic modification. Commented Oct 2, 2010 at 18:25
  • I would recommend he learn a little more about generics, maybe. If I had come from python to java (instead of vice versa) generics would seem really odd at first. Commented Oct 2, 2010 at 18:36

4 Answers 4

8

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, ...

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.