To access elements in a list in Java, you can use indexing or iterate over the list using loops.
In this example,
numList
with integer elements.get()
method and print them to standard output.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numList = new ArrayList<>();
numList.add(1);
numList.add(2);
numList.add(3);
int element = numList.get(2); // Accessing element at index 2
System.out.println("Element at index 2: " + element);
}
}
Element at index 2: 3
In this example,
strList
with string elements.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> strList = new ArrayList<>();
strList.add("Apple");
strList.add("Banana");
strList.add("Cherry");
for (String str : strList) {
System.out.println(str);
}
}
}
Apple Banana Cherry
In this tutorial, we learned How to Access Elements in a List in Java language with well detailed examples.