为什么要使用 ‘iterator’ 遍历 ArrayList。不使用迭代器也可以完成,对吗?

huangapple go评论117阅读模式
英文:

why to use 'iterator' to loop thru an ArrayList. It can be done without Iterator also right?

问题

为什么要使用 'iterator' 来遍历 ArrayList?也可以不使用 Iterator 来完成,对吗?
所以使用 Iterator 来遍历 ArrayList 的好处是什么?

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorDemo {
  public static void main(String[] args) {

    // 创建一个集合
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");

    // 获取迭代器
    // Iterator<String> it = cars.iterator();

    // 在没有使用 Iterator 的情况下循环
    for (int i = 0; i < 4; i++) {
      //System.out.println(it.next());

      System.out.println(cars.get(i));
    }
  }
}
英文:

why use 'iterator' to loop thru an ArrayList. It can be done without Iterator also right?
so the benefits of using iterator to loop thru an ArrayList

import java.util.ArrayList;
import java.util.Iterator;

 public class IteratorDemo {
  public static void main(String[] args) {

    // Make a collection
    ArrayList&lt;String&gt; cars = new ArrayList&lt;String&gt;();
    cars.add(&quot;Volvo&quot;);
    cars.add(&quot;BMW&quot;);
    cars.add(&quot;Ford&quot;);
    cars.add(&quot;Mazda&quot;);

    // Get the iterator
    //Iterator&lt;String&gt; it = cars.iterator();

    // Looping without Iterator
    for(int i=0;i&lt;4;i++) {
        //System.out.println(it.next());

        System.out.println(cars.get(i));
    }
  }
 }

答案1

得分: 1

有时候你只是不需要索引,这样会更简单。但是尝试使用带索引的循环来做这个。这是可以做到的,但不会那么简单。

List<Integer> list = new ArrayList<>(
                List.of(1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10));
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
   // 如果是偶数,移除它。
   if (it.next() % 2 == 0) {
      it.remove();
   }
}
System.out.println(list);

打印结果

[1, 3, 5, 7, 9]

使用 Iterator 允许你修改可能会触发并发修改异常的列表。

另外,假设你有一个生成素数或斐波那契数的类实现。你可以这样单独获取它们。

Fibonacci fib = new Fibonacci(0, 1, 10);
for (long i : fib) {
    System.out.print(i + " ");
}

打印结果

0 1 1 2 3 5 8 13 21 34 

Fibonacci 类

class Fibonacci implements Iterable<Long> {
    public long start;
    public long next;
    public long count;

    public Fibonacci(int start, int next, int count) {
        this.start = start;
        this.next = next;
        this.count = count;
    }

    private class MyIterator implements Iterator<Long> {
        int n = 0;

        public boolean hasNext() {
            return n < count;
        }

        public Long next() {
            n++;
            long ret = start;
            start = start + next;
            next = ret;
            return ret;
        }
    }

    public Iterator<Long> iterator() {
        return new MyIterator();
    }
}

通过在类中实现 Iterable,我可以使用 foreach 结构来获取类的元素。

英文:

Sometimes you just don't need the index so it is easier. But try doing this using an indexed for loop. It can be done, but not as easily.

List&lt;Integer&gt; list = new ArrayList&lt;&gt;(
				List.of(1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10));
Iterator&lt;Integer&gt; it = list.iterator();
while (it.hasNext()) {
   // if even, remove it.
   if (it.next() % 2 == 0) {
      it.remove();
   }
}
System.out.println(list);

Prints

[1, 3, 5, 7, 9]

Using an interator allows you to modify lists that might otherwise trigger a concurrent modification exception.

Also, assume you had a class implementation that generated primes or fibonacci numbers. You could do this to grab them individually.

Fibonacci fib = new Fibonacci(0, 1, 10);
for (long i : fib) {
	System.out.print(i + &quot; &quot;);
}

Prints

0 1 1 2 3 5 8 13 21 34 

The Fibonacci class

class Fibonacci implements Iterable&lt;Long&gt; {
	public long start;
	public long next;
	public long count;
	
	public Fibonacci(int start, int next, int count) {
		this.start = start;
		this.next = next;
	    this.count = count;
	}
	
	private class MyIterator implements Iterator&lt;Long&gt; {
		int n = 0;
		
		public boolean hasNext() {
			return n &lt; count;
		}
		
		public Long next() {
			n++;
			long ret = start;
			start = start + next;
		    next = ret;
			return ret;
		}
	}
	
	public Iterator&lt;Long&gt; iterator() {
		return new MyIterator();
	}
}

By implementing Iterable in the class I can use the foreach construct to get elements of the class.

答案2

得分: 0

你可能没有直接使用它的好处。但是迭代器例如被 forEach 使用。

英文:

You probably don't have benefit of using it directly. But the iterator is used by for example the forEach.

答案3

得分: 0

只需循环遍历,不需要迭代器,for循环就足够了。如果需要修改列表,则需要使用迭代器以避免ConcurrentModificationException。

英文:

Just to loop through it you don't need an iterator, a for loop will suffice. If you need to modify the list then you need it to avoid ConcurrentModificationException.

huangapple
  • 本文由 发表于 2020年10月12日 03:20:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64308097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定