开发者

IntelliJ suggests replacing the while loop with a for each loop. Why?

开发者 https://www.devze.com 2023-04-12 01:40 出处:网络
ArrayList<Obj开发者_如何转开发ect> list = new ArrayList<Object>(); list.add(12); list.add(\"Hello\");
    ArrayList<Obj开发者_如何转开发ect> list = new ArrayList<Object>();
    list.add(12);
    list.add("Hello");
    list.add(true);
    list.add('c');

    Iterator iterator = list.iterator();
    while(iterator.hasNext())
    {
        System.out.println(iterator.next().toString());
    }

When I enter this Java code in IntelliJ IDEA, the code analysis feature suggests that I replace the while loop with a for each loop since I'm iterating on a collection. Why is this?


This is what it wants you to use:

for (Object o : list)
{
    System.out.println(o.toString());
}

This has been in the language since Java 1.5, and is the idiomatic pattern. You need the Iterator only if you need access to the iterator's other methods (i.e. remove()).


Because you are less likely to make mistakes and it looks better ; )

for( Object obj : list ) {
  System.out.println( obj.toString() );
}


because you have the inspection Java Language Migration Aids - 'while' loop replaceable with 'for each' active (which is the default), description is

This inspection reports for loops which iterate over collections or arrays, and can be replaced with the "for each" iteration syntax, available in Java 5 and newer. The setting Report java.util.List indexed loops is responsible for finding loops involving list.get(index) calls. These loops generally can be replaced with the foreach loops, unless they modify underlying list in the process, e.g. by calling list.remove(index). If latter is the case, foreach form of loop may throw ConcurrentModificationException. This inspection only reports if the project or module is configured to use a language level of 5.0 or higher.

so if you don't want to be told this then uncheck that box in the Inspections config


The foreach loop is shorter to write and thus easier to read.


The Foreach Loop however creates an anonymous class and consumes more memory compared to while loop, i would suggest to ignore the suggestion and use the while loop for better and optimized use of your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消