ArrayList Iteration Methods in Java
Several methods for traversing an ArrayList collection include:
- Use a for loop to iterate through a collection by indexing. You can use the size() method of an ArrayList to get the size of the collection, and then loop through each element.
ArrayList<String> list = new ArrayList<>();
// 添加元素到集合中
for (int i = 0; i < list.size(); i++) {
String element = list.get(i);
// 处理每个元素
}
- Traverse using an iterator: Obtain an iterator object with the iterator() method in ArrayList, then use a while loop with the hasNext() method to check for the next element, and use the next() method to retrieve it.
ArrayList<String> list = new ArrayList<>();
// 添加元素到集合中
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
// 处理每个元素
}
- Traverse using a foreach loop: Use a foreach loop to directly iterate through each element in the collection.
ArrayList<String> list = new ArrayList<>();
// 添加元素到集合中
for (String element : list) {
// 处理每个元素
}
When traversing a collection using a foreach loop, it is not allowed to modify the elements in the collection, otherwise a ConcurrentModificationException will be thrown. If you need to modify the elements in the collection, you can use the remove() method of the iterator.