Java Collection collection traversal running code example

Iterator: Iterator, the special traversal method of the collection
Iterator iterator(): Returns the iterator of the elements in this collection, the iterator obtained
by the iterator() method of the collection is obtained by the iterator() method of the collection, so we say it is Depends on the existence of the collection

Common methods in Iterator
E next(): returns the next element in the iteration
boolean hasNext(): returns true if the iteration has more elements

code show as below

public class CollectionDemo_01 {
  public static void main(String[] args) {
    //创建集合对象
    Collection<String> c = new ArrayList<String>();

    //添加元素
    c.add("hello");
    c.add("world");
    c.add("java");

    //Iterator <E> iterator() : 返回此集合中元素的迭代器,通过集合的iterator()方法得到
    Iterator<String> it = c.iterator();


    /*
      阅读源码可以知道,iterator方法,返回了一个实现Iterator<E>接口的具体实现类Itr所创建的对象
      public Iterator<E> iterator() {
        return new Itr();
      }

      private class Itr implements Iterator<E> {}
     */

    //使用while循环遍历集合
    while (it.hasNext()){
      String s = it.next();
      System.out.println(s);
    }
    
    /*
      运行结果:
        hello
        world
        java
     */
  }
}

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113925276