0

I got a Basic String Array

String[] array = {
        "AAA",
        "BBB",
        "CCC"
    };

Now I want to add a new Item to it

array[array.length + 1] = "DDD"

After I run my application it crashs.

1

3 Answers 3

2

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Java docs

If you want to change the size dynamically then you should use an ArrayList

or you could also use a HashMap

Android docs on ArrayList

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

Comments

0
array[array.length + 1] = "DDD"

here assume array.length is 3 in your case its 3 cause you initialsed in such way so its 3 so when your trying to insert value in it you cant insert value in index which not in its bound so your upper limit index is its length-1 (cause index starts from 0)

because your trying to acess index which is out of bounds you will get ArrayIndexOutOfBounds exception thats why your getting crashes in your app hope it clears your issue

Comments

0

You can use a ArrayList instead.

Just write

List<String> array = new ArrayList<String>();

array.add("AAA");
array.add("BBB");
array.add("CCC");
array.add("DDD");

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.