To iterate over an ArrayList
in Java, you can use various approaches, such as using a for loop, an enhanced for loop (for-each loop), or an iterator.
Here are examples of each approach:
- Using a for loop:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (int i = 0; i < numbers.size(); i++) {
int element = numbers.get(i);
System.out.println(element);
}
- Using an enhanced for loop (for-each loop):
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (int element : numbers) {
System.out.println(element);
}
- Using an iterator:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
System.out.println(element);
}
All three approaches will produce the same output:
10 20 30
In the for loop approach, we iterate over the indices of the ArrayList
using the size()
method and access each element using the get()
method.
In the enhanced for loop approach, we directly iterate over each element in the ArrayList
. This approach is simpler and more concise.
In the iterator approach, we obtain an iterator from the ArrayList
using the iterator()
method. We then use the hasNext()
method to check if there are more elements and the next()
method to retrieve the next element.
0 Comments