-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?

Hayley van Waas
  • 429
  • 3
  • 12
  • 21

4 Answers4

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

Naveen
  • 535
  • 3
  • 14
  • Check out this http://stackoverflow.com/questions/5061721/how-can-i-dynamically-add-items-to-a-java-array – Naveen May 05 '14 at 09:42
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
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
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.

arghtype
  • 4,376
  • 11
  • 45
  • 60
-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

Xavjer
  • 8,838
  • 2
  • 22
  • 42