JAVA中的for循环几种使用方法 | 您所在的位置:网站首页 › 2有几种写法 › JAVA中的for循环几种使用方法 |
一般写法
1: 遍历数组的传统方式
/* 建立一个数组 */
int [] integers={1,2,3,4};
/* 开始遍历 */
for (int j=0;j"A", "B", "C", "D"};
Collection stringList = java.util.Arrays.asList(strings);
/* 开始遍历 */
for (Iterator itr = stringList.iterator(); itr.hasNext();) {
Object str = itr.next();
System.out.println(str);
}
第二种写法
for (循环变量类型 循环变量名称 : 要被遍历的对象) 循环体 3:遍历数组的简单方式 /* 建立一个数组 */ int[] integers = {1, 2, 3, 4}; /* 开始遍历 */ for (int i : integers) { System.out.println(i); /* 依次输出“1”、“2”、“3”、“4” */ } 遍历数组的简单方式的等价代码 /* 建立一个数组 */ int[] integers = {1, 2, 3, 4}; /* 开始遍历 */ for (int 变量名甲 = 0; 变量名甲 "A", "B", "C", "D"}; Collection list = java.util.Arrays.asList(strings); /* 开始遍历 */ for (Object str : list) { System.out.println(str); /* 依次输出“A”、“B”、“C”、“D” */ } 遍历数组的简单方式的等价代码 /* 建立一个Collection */ String[] strings = {"A", "B", "C", "D"}; Collection stringList = java.util.Arrays.asList(strings); /* 开始遍历 */ for (Iterator 变量名乙 = list.iterator(); 变量名乙.hasNext();) { Object str = 变量名乙.next(); System.out.println(str); /* 依次输出“A”、“B”、“C”、“D” */ } 防止在循环体里修改循环变量 5:禁止重新赋值 int[] integers = {1, 2, 3, 4}; for (final int i : integers) { i = i / 2; /* 编译时出错 */ }这只是禁止了对循环变量进行重新赋值。给循环变量的属性赋值,或者调用能让循环变量的内容变化的方法,是不被禁止的。 循环变量的类型可以是要被遍历的对象中的元素的上级类型。 例如,用int型的循环变量来遍历一个byte[]型的数组,用Object型的循环变量来遍历一个Collection< String>(全部元素都是String的Collection)等。 9:使用要被遍历的对象中的元素的上级类型的循环变量 String[] strings = {"A", "B", "C", "D"}; Collection list = java.util.Arrays.asList(strings); for (Object str : list) { System.out.println(str);/* 依次输出“A”、“B”、“C”、“D” */ } 10:使用能和要被遍历的对象中的元素的类型自动转换的类型的循环变量 int[] integers = {1, 2, 3, 4}; for (Integer i : integers) { System.out.println(i); /* 依次输出“1”、“2”、“3”、“4” */ }注意,这里说的“元素的类型”,是由要被遍历的对象的决定的――如果它是一个Object[]型的数组,那么元素的类型就是Object,即使里面装的都是String对象也是如此。 参考博客:https://www.cnblogs.com/hellochennan/p/5373186.html |
CopyRight 2018-2019 实验室设备网 版权所有 |