数组、集合常见遍历方法
一、for循环
数组的遍历:数组的for循环主要是通过arr.length,来获取数组的长度,使用for循环进行,进行循环,获取出每一个数组元素,打印元素。
/**
* 通过基本的for循环进行遍历
*/
public static void traverseByFor(int[] arr) {
if (arr == null) {//首先判定数组是否为空
return;
}
System.out.println("以下是通过基本for循环的遍历结果");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
集合遍历:list集合的for循环主要是通过list.length(),来获取集合的长度,使用for循环进行,进行循环,获取出每一个集合元素,打印元素。
//常用遍历list集合的方式
List<String> list=new ArrayList<String>();//定义一个字符串类型的集合
list.add("D");//分别向集合中加入A、B、C、D四个元素
list.add("B");
list.add("A");
list.add("C");
System.out.println("常规for循环