數組對於每一門編程語言來說都是重要的數據結構之一,當然不同語言對數組的實現及處理也不盡相同。
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、閱讀到此的大佬如果還有其他方式請留言。。。,如果討論技術問題可以私聊我。