[Reserved] (Detailed as well as the difference between iterator and for loop) Java iterators

Java iterators (iterator explain the difference and for cycling as well as)

Find useful, welcome to discuss mutual learning ~ [Follow]

  • Reprinted from https://blog.csdn.net/Jae_Wang/article/details/80526216

    Foreword

  • Iterator is a pattern, design pattern which can be seen in detail, the data structure may be such that a sequence of traversal behavior type of separation with the object to be traversed, i.e., we do not care about the underlying structure of the sequence of what is. Just get this object, use the iterator can traverse the interior of the object
  • Iterable implementation of this interface is a collection of objects to support iteration is iteration. This can be achieved with the use foreach ~
  • Iterator iterator, provides an object iterative mechanism, specifically, how is this iteration Iterator interface specification.
//Iterable JDK源码
//可以通过成员内部类,方法内部类,甚至匿名内部类去实现Iterator

public interface Iterable<T>
{

    Iterator<T> iterator();
  • Iterable there is a default method forEach ()
  • The Iterator interface: contains three methods: hasNext, next, remove, remove rarely used.

public interface Iterator<E> {


    boolean hasNext();    //每次next之前,先调用此方法探测是否迭代到终点

    E next();            //返回当前迭代元素 ,同时,迭代游标后移


     /*删除最近一次已近迭代出出去的那个元素。
     只有当next执行完后,才能调用remove函数。
     比如你要删除第一个元素,不能直接调用 remove()   而要先next一下( );
     在没有先调用next 就调用remove方法是会抛出异常的。
     这个和MySQL中的ResultSet很类似
    */
    void remove()
    {
        throw new UnsupportedOperationException("remove");
    }

Note

  • Iteration out of the elements are a collection of copies of the original elements.
  • Save the Java elements in the collection is the essence of an object reference, not the object itself.
  • Iteration of the object is referenced by a copy of the results or references. So if you save a collection of elements is a variable type, you can modify the original objects in the collection by iterating the elements.
import java.util.ArrayList;
import java.util.Iterator;

public class test {
    public static void main(String[] args) {
        ArrayList<Person> array = new ArrayList<Person>();

        Person p1 = new Person("Tom1");
        Person p2 = new Person("Tom2");
        Person p3 = new Person("Tom3");
        Person p4 = new Person("Tom4");

        array.add(p1);
        array.add(p2);
        array.add(p3);
        array.add(p4);

        Iterator<Person> iterator = array.iterator();

        for (Person pp : array){
            System.out.println(pp.getName());
        }

        System.out.println("\r\n" + "-----利用Lambda表达式的foreach-----" + "\r\n");
        array.forEach(obj -> System.out.println(obj.getName()));


        System.out.println("\r\n" + "-----利用for循环-----" + "\r\n");
        for(Person p : array){
            p.setName("wang");
        }

        while(iterator.hasNext()){
            System.out.println(iterator.next().getName()); //输出的是wang,而不是tom
        }



    }
}

Map traversal is the same -

public static void main(String[] args) {
        Map map = new HashMap();
        for(int i = 0; i < 10; i ++){
            map.put(i, String.valueOf("map" + i));
        }
        Iterator iterMap = map.entrySet().iterator();
        while(iterMap.hasNext()){
            Map.Entry strMap = (Map.Entry)iterMap.next();
            System.out.println("key为:" + strMap.getKey() +
                    ", value为:" + strMap.getValue());
        }
    }

Then when an Iterator access Collection elements in the collection, Collection of elements can not change (modify multiple threads), only () method to delete the last time next () method returns remove Iterator through the collection can. This will lead to ModificationException an exception, that is fail-fast mechanism

//创建集合,添加元素和上述一样      
        Iterator<Person> iterator = array.iterator();

      while(iterator.hasNext()){
         String name = iterator.next().getName();
         System.out.println(name);
         if(name.equals("Tom3")){
             //array.remove(name);  不推荐这种方式
             iterator.remove();
         }
      }

Iterator and generics with:

  • Iterator implementation class for any set of classes, can return such an Iterator object. It can be applied to any class.
  • Because collection classes (List, and Set, etc.) can be loaded into the type of the object is uncertain, when removed from the collection are of type Object with a time of need to be forcibly converted, it will be very troublesome, and use generics, it is to advance tell a collection sure you want to mount the type of the collection so that it can be used directly without conversion display type. very convenient.

    foreach and Iterator relationship:

  • for each element in the set to be used to process each of the set of set without considering scale. It is to make a simple Iterator. But deleted when the difference is the call to remove the collection will lead to changes result in an error in the original collection remove, cycle, but should use the remove method of the iterator.

    Use a for loop or iterator Iterator contrast

  • ArrayList using faster random access, and the for loop get () method, i.e. using a random access method, so ArrayList in, for faster cycle
  • LinkedList uses sequential access is relatively fast, the iterator Next () method, i.e. a method of using sequential access, so LinkedList, the use of faster iterator
  • From the data structure point of view, suitable for loop structure access sequence, the subscript can quickly obtain the specified element. Iterator for accessing the chain structure, because the iterator by next () and PreS () to locate in. Order not accessible collection.
  • The advantage of using the Iterator may be used in the same way that the element in the collection to traverse, without regard to the internal implementation classes (as long as it implements the interface java.lang.Iterable), if the Iterator to traverse element in the collection, once no longer in use List switch to Set to organize the data, code that traverse the elements do not make any changes, if used for to iterate, iterate that all of this collection algorithm had to be adjusted accordingly, because orderly List, Set disorder, different structures, their access algorithms are not the same. (still illustrates the point traversal and the collection itself separated)

Guess you like

Origin www.cnblogs.com/cloud-ken/p/11303084.html