版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aitangyong/article/details/54896454
以数组为例,基本上有下面4种常见的遍历方式:
public class Test {
public static void main(String[] args) {
// 方式1
for (int i = 0; i < Test.array().length; i++) {
}
System.out.println("---");
// 方式2
int length = Test.array().length;
for (int i = 0; i < length; i++) {
}
System.out.println("---");
// 方式3
for (int i = 0, size = Test.array().length; i < size; i++) {
}
// 方式4
System.out.println("---");
for (int i : Test.array()) {
}
}
public static int[] array() {
System.out.println("array");
int[] result = {1, 2, 3};
return result;
}
}
方式1:多次调用函数,而这些调用是不必要的,浪费
方式2:引入了额外的length变量,而且该变量在整个方法作用域内都可见,有变量作用域污染问题
方式3:不存在方式1的浪费,不存在方式2的作用域污染,唯一不好的地方在于多定义一个变量
方式4:不存在方式1的浪费,不存在方式2的作用域污染,唯一不好的地方在于丢失了索引信息。
总之:不需要索引的时候使用方式4,需要索引的时候使用方式3。