Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList internal working

I wanna test how the indexing work in case of arrayList. When I try to add element at a specified index say arrlist.add(15, "shreyas"); I get an Exception "IndexOutOfBoundException".. why is that so?? I am confused. please help..!!! Thanks in advance

ArrayList <String> arrlist = new ArrayList <String>(20);
          arrlist.add(15, "shreyas");
          arrlist.add(18, "jp");

          for(int i=0;i<arrlist.size();i++){
                 System.out.println("Index is i="+i+" And Element is "+arrlist.get(i));
   }
like image 555
Shreyas Deshpande Avatar asked Jul 09 '26 07:07

Shreyas Deshpande


1 Answers

The ArrayList can't have gaps. You can't add an element to the 15'th position if you haven't added elements to the 0 to 14 positions first.

like image 57
Eran Avatar answered Jul 11 '26 06:07

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!