-4

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));
        }

    }

}
koki
  • 39
  • 6

1 Answers1

0

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.

see sharper
  • 11,505
  • 8
  • 46
  • 65