Java 中数组的遍历方式

时间:2023-03-08 15:56:49

数组对于每一门编程语言来说都是重要的数据结构之一,当然不同语言对数组的实现及处理也不尽相同。

Java 语言中提供的数组是用来存储固定大小的同类型元素。

今天我们就来说一下在java中遍历数组都有哪几种方式:

假如有下面数组arry

Integer[] arry= {1,2,3,4,5,6,7};

针对以上数组进行遍历,在java中我们常用到的就是for循环

1、这种方法简单粗暴易使用

for(int i = 0; i < arry.length; i++){
system.out.println(arry[i])
}

2、利用forEach遍历(这种方式简单方便)

for(Integer x : arry){
system.out.println(x)
}

3、这种方式比较烦,一般不建议使用,没有for循环和forEach简单

Integer[] arry = {1,2,3,4,5};
List<Integer> list = Arrays.asList(arry);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}

4、stream遍历(此方法来自java8)

Arrays.asList(arry).stream().forEach(x -> System.out.println(x));
也可以这样写:
Arrays.asList(arry).stream().forEach(System.out::println);

5、阅读到此的大佬如果还有其他方式请留言。。。,如果讨论技术问题可以私聊我。