Hi Everyone,
I'm running into an issue with a Java ArrayList, and I'm hoping someone can help me out. I keep getting an "Index out of range" error when trying to access elements. Here's a snippet of what I'm dealing with:
**import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList myList = new ArrayList<>();
myList.add("First Element");
String element = myList.get(1); // IndexOutOfBoundsException
System.out.println(element);
}
}
**
I'm puzzled because I've only added one element to the list, so shouldn't it be at index 0? Why am I getting an exception when trying to access index 1? If you've encountered this before or have any idea what might be going on, your input would be greatly appreciated.
Top comments (1)
Hi Sam, the answer:
Arrays in Java are zero-indexed, which means that the first element in an array has an index of 0, the second element has an index of 1, and so on
Reference: freecodecamp.org/news/how-to-creat....