IndexOutOfBoundsException when added to ArrayList by index

I get an exception Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0for the code below. But I could not understand why.

public class App {
    public static void main(String[] args) {
        ArrayList<String> s = new ArrayList<>();

        //Set index deliberately as 1 (not zero)
        s.add(1,"Elephant");

        System.out.println(s.size());                
    }
}

Update

I can make it work, but I'm trying to understand the concepts, so I changed the ad below, but didn't work.

ArrayList<String> s = new ArrayList<>(10)
+4
source share
9 answers

ArrayList index starts at 0 (zero)

The size of your array is 0, and you add a String element to the 1st index. Without adding an element to the 0th index, you cannot add the following index positions. It is not right.

So just do it like

 s.add("Elephant");

Or you can

s.add(0,"Elephant");
+2
source

Your is ArrayListempty. Using this line:

s.add(1,"Elephant");

"Elephant" 1 ArrayList ( ), , IndexOutOfBoundsException.

s.add("Elephant");

.

+4

ArrayList , 0, 1 .

, -

String[] strings = new String[5];
strings[1] = "Elephant";

List<String> s = Arrays.asList(strings);
System.out.println(s); 

[null, Elephant, null, null, null]
+4

"" 1, (, ) 0.

public class App {
public static void main(String[] args) {
    ArrayList<String> s = new ArrayList<>();

    s.add(null);
    s.add("Elephant");

    System.out.println(s.size());                
  }
}

.add, null 0 1.

+1

Android:

, , SparseArray memory (a ArrayList null).

:

SparseArray<String> list = new SparseArray<>();
list.put(99, "string1");
list.put(23, "string2");
list.put(45, "string3");
  • list.append(), , 1, 2, 3, 5, 7, 11, 13...
  • list.put(), , 100, 23, 45, 277, 42...

, HashMap, .

+1

add(int index, E element) API : , 1-

:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

boolean add(E e).

UPDATE

, , , .

ArrayList<String> s = new ArrayList<>(10)

new ArrayList<Integer>(10), 10, . , .

0

ArrayList . 1, # 0.

0
 class App {
    public static void main(String[] args) {
        ArrayList<String> s = new ArrayList<String>();

        //Set index deliberately as 1 (not zero)
        s.add(0,"Elephant");
        System.out.println(s.size());                
    }
}
0

Do not add the index as 1 directly to the list. If you want to add a value to the list, add it like this: s.add ("elephant"); By default, the size of the list is 0. If you add any items to the list, the size will automatically increase; you cannot directly add the 1st index to the list. //s.add(0, "Elephant");

0
source

Source: https://habr.com/ru/post/1538032/


All Articles