-2

I have an array, defined as below:

String[] letters = {"ab", "cd", "ef", "gh"};

How would I go about adding an item to this array?

4

4 Answers 4

2

1.Arrays are fixed in size

2.Before declaring an array we should know the size in advance.

3.We cannot add anything dynamically to an array once we declare its size.

I recommend you to go for collection framework like List or Set where you can increase the size dynamically

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

1 Comment

1

By using this type of array initialization you cannot simply add more elements.

String[] letters = {"ab", "cd", "ef", "gh"};

Could be paraphrased as:

String[] letters = new String[4];
letters[0] = "ab";
letters[1] = "cd"; 
letters[2] = "ef";
letters[3] = "gh";

So, your array's length is only 4. To add more elements you should somehow copy you array to a bigger one and add elements there. Or just use ArrayList which does the hard work for you when capacity is exceeded.

Comments

1

Java arrays having static size. One you define the size of a array, it can't grow further dynamically.

Your letters array has a size of 4 element. So, you can't add more element to it.

Use ArrayList instead

List<String> letters = new ArrayList(); // Java 7 and upper versions
letters.add("ab");
letters.add("cd");
....// You can add more elements here

5 Comments

@HayleyvanWaas : Check updated answer with example
Downvoter: Please specify the reason for that.
Seeing the list of duplicates of this question, I think the reason for the downvote is pretty clear. There's absolutely no need to have another copy with the same answers and examples on SO.
@SvenT23 : It can't be done by closing the question instead. That's the recommended way of doing.
I thought the recommended way of doing things was referring to the duplicate with the flag to close it, not answering the question again :) According to my knowledge, that solves her problem and gets rid of this copy faster.
-1

This is not possible without a workaround like http://www.mkyong.com/java/java-append-values-into-an-object-array/

try ArrayList, List, Map, HashMap or something like this instead

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.