Java – loop through the list, a better way

When I write and discover new ways of working in Java, I'm always confused about the better way to loop lists to output data

In the following example, I recycle counters through lists, and many times I have to include an index counter in the output

I prefer method 1, but I find these methods a little outdated I've seen many examples. Through list loop, method 2 is mostly used

So my question is what is the better method? If all these methods are the same, what is the most standard?

private ArrayList<String> list = new ArrayList<String>();

public test() {
    list.add("One");        
    list.add("Two");        
    list.add("Three");      
    list.add("Four");       
    list.add("Five");

    method1();
    method2();
    method3();
}

public void method1() {
    System.out.println("Method 1");
    int i = 1;
    for (String value:list) {
        System.out.println((i++) + " = " + value);
    }
}

public void method2() {
    System.out.println("Method 2");
    for (int i = 0; i < list.size(); i++) {
        System.out.println((i+1) + " = " + list.get(i));
    }
}

public void method3() {
    System.out.println("Method 3");
    Iterator<String> it = list.iterator();
    int i = 1;
    while (it.hasNext()) {
        System.out.println((i++) + " = " + it.next());
    }
}

Solution

Method1 () is similar to method3 (), because the for - each loop uses the iterator of the list behind the scenes The difference from method3 () is that you can actually access this iterator, so if you want to remove an element from the list, you can call remove

On the other hand, method 2 () can lead to "poor" performance, depending on the underlying implementation If your list is LinkedList, get has o (n) complexity time, so for loop will have o (n ^ 2) complexity With iterators, you will always get the next element in uninterrupted time

I personally use 1, which also reduces writing code, which is one of the main advantages of the for each loop if your intention is to perform read-only operations on data structures

If you are using java 8 and do not need to print the index, you can also do the following:

list.forEach(System.out::println);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>