可以发现,原来增强for循环是依赖了while循环和Iterator实现的。规范中指出不让我们在foreach循环中对集合元素做add/remove操作,那么,我们尝试着做一下看看会发生什么问题。 private static void test() { List<String> names = new ArrayList<String>() {{ add("Hello"); add("
}longarrayListForeachCost=System.currentTimeMillis()-arrayListForeachStartTime; System.out.println("ArrayList foreach traversal cost: "+ arrayListForeachCost); 这是测试结果: 如你所见,结果是显而易见的。对于ArrayList,使用For循环方法的性能优于For each方法。 我们可以说for循环比for-each好吗? 答案是否...
现在让我们使用for循环方法和for-each方法进行测试。 代码语言:java AI代码解释 publicclassForLoopTest{publicstaticvoidmain(String[]args){List<Integer>arrayList=newArrayList<>();for(inti=0;i<10000000;i++){arrayList.add(i);}longarrayListStartTime=System.currentTimeMillis();for(inti=0;i<arrayList.size...
import java.util.ArrayList; import java.util.List; public class IterateListTest { public static void main(String[] args) { List<Integer> mylist = new ArrayList<>(); for (int i = 0; i < 1000000; i++) { mylist.add(i); } long forLoopStartTime = System.currentTimeMillis(); for ...
for (Iterator<String> iterator = actors.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } 1. 2. 3. (for-each (Enhanced for loop)) This loop was introduced in Java 5, it removes the clutter, ceremony and the opportunity for error by hiding the iterator or in...
Classic for loop 首先,来看看classic for loop. List<String> birds =new ArrayList<String>() { { add("magpie"); add("crow"); add("emu"); } }; for (int i =0; i < birds.size(); i++) { String bird = birds.get(i); }
以下是Java中的for循环的示例代码。 publicclassTest{publicstaticvoidmain(Stringargs[]){for(intx=10;x<20;x=x+1){System.out.print("value of x : "+x);System.out.print("\n");}}} Java Copy 这将产生以下结果− 输出 value of x:10value of x:11value of x:12value of x:13value of ...
For-Each 是 Java5 中引入的另一种数组遍历技术,它以类似于常规for循环的关键字开头具有以下特点: 无需声明和初始化循环计数器变量,而是声明一个与数组的基本类型相同类型的变量,然后是冒号,然后是冒号,然后是数组名。 在循环主体中,可以使用创建的循环变量,而不是使用索引数组元素。
⾸先,来看看classic for loop.List<String> birds = new ArrayList<String>() { { add("magpie");add("crow");add("emu");} };for (int i = 0; i < birds.size(); i++) { String bird = birds.get(i);} 这种⽅式,代码风格还好,可惜的是,有个隐藏的性能问题。对于List接⼝的众多...
Test.java 文件代码: publicclassTest{publicstaticvoidmain(String[]args){for(intx=10;x<20;x=x+1){System.out.print("value of x :"+x);System.out.print("\n");}}} 以上实例编译运行结果如下: value of x:10value of x:11value of x:12value of x:13value of x:14value of x:15value...