How to traverse an array using a Java iterator?
You can use a Java iterator to traverse an array, the specific steps are as follows:
- Create an array object, which can be either an array of primitive data types or an array of objects.
- Convert the array object to a collection object using the asList() method of the Arrays class.
- Obtain an iterator object using the iterator() method of a collection object.
- Traverse the array using a while loop and the hasNext() and next() methods of an iterator.
Here is an example code:
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 创建数组对象
Integer[] array = {1, 2, 3, 4, 5};
// 将数组对象转换为集合对象
List<Integer> list = Arrays.asList(array);
// 使用集合对象的iterator()方法获取迭代器对象
Iterator<Integer> iterator = list.iterator();
// 使用while循环和迭代器的hasNext()和next()方法遍历数组
while (iterator.hasNext()) {
Integer element = iterator.next();
System.out.println(element);
}
}
}
Running the code above will result in:
1
2
3
4
5