Java – which method works best when I traverse a list?

List<T> list = new ArrayList<T>();
List<T> list = new ArrayList<T>();

1 method:

for(int i = list.length - 1; i >= 0; i--) {
  System.out.println(list.get(i));
}

2. Method:

for(T t : list) {
  System.out.println(t);
}

3. Method:

Iterator<T> it = list.iterator();     
while(it.hasNext()) {
  System.out.println(it.next());
}

Solution

Efficiency is unlikely to be significant – of course, system out. Println is more likely to be a bottleneck in your particular example

The second method (enhanced loop) is the most readable Note that these three methods will not do the same thing - the first method will iterate from the end rather than from the beginning Getting the right behavior is almost always better than a few. Hurry up The more readable your code is, the more likely you are to be correct

Seek readability and measure the performance of the application if it becomes a problem, micro optimization bottleneck (continue to measure each step)

Edit: my answer is based on the first line of the question, showing that an ArrayList < T > is in use

If you want an answer to any list < T >, there is no accurate answer at all List and lt; T> No guarantee of complexity is provided It doesn't say how fast you should achieve, nor how fast you expect the iterator to be You may be using an implementation with good random access, but this is a very slow iterator This is unlikely, but it is still a valid list < T >

In short: if you're worried about efficiency, you need to know what list you're using In general, iterations may be reasonably effective, and random access may or may not be effective (it may be more effective than iteration, but it is unlikely to significantly improve efficiency.) In practice, my experience is that in most applications, you actually have enough knowledge to make reasonable judgments... But I usually write code for readability first

As others have pointed out, if you really want to use random access to get elements, it's worth ensuring that your list also implements the randomaccess interface

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
分享
二维码
< <上一篇
下一篇>>