Why is Java giving my ArrayList an IndexOutOfBoundsException?

Why is Java giving me an error message? Im using JavaSE-12 and don't understand why I have an IndexOutOfBoundsException. Do I have to specify the index of the ArrayList or what am I missing?

    import java.util.ArrayList;


public class DSArrayList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<String> namensListe = new ArrayList<String>();

        namensListe.add("Hans");
        namensListe.add("Peter");

        for(int i = 0; i <= namensListe.size(); i++) {
            System.out.println("Name: " + namensListe.get(i));
        }

    }

}

1 answer

  • answered 2020-06-02 10:30 see sharper

    for(int i = 0; i < namensListe.size(); i++)

    (note the < operator)

    To explain, arrays and like structures are indexed from zero, not one. Obviously we count, however, from one, not zero. So the length of an array is always one greater than the index of the last item it contains.