Java Container---iterators

Source: Internet
Author: User

Any container class must have some way to insert elements and retrieve them again. After all, holding things is the most basic work of a container. For list, add0 is one of the methods of inserting elements, and get () is one of the methods for extracting elements.

If you think from a higher level, you will find that there is a drawback: to use a container, you must program the exact type of container. At first glance this is nothing bad, but consider the following situation: If the original is the list encoding, but later found that if you can apply the same code to set, it will be very convenient, what should be done? Or are you going to write generic code from scratch, and they just use containers, don't know or care about the types of containers, so how can you apply them to different types of containers without rewriting the code?

The concept of an iterator (also a design pattern) can be used for this purpose. An iterator is an object whose work is to traverse and select the objects in the sequence, and the client programmer does not have to know or care about the underlying structure of the sequence . In addition, iterators are often referred to as lightweight objects: the cost of creating it is small. As a result, there are often strange restrictions on iterators, for example, Java's Iterator can only be moved one way, and this Iterator can only be used to:

(1) Use Method iterator () requires the container to return a iterator. Iterator will be ready to return the first element of a sequence.

(2) Use next () to get the next element in the sequence.

(3) Use Hasnext () to check if there are elements in the sequence.

(4) Remove the newly returned element of the selector using remove () .

with iterator you don't have to worry about the number of elements in the container, which is something that Hasnext () and Next () cares about. If you just walk forward through the list and do not intend to modify the list object itself, you can see that the foreach syntax is more concise.

Iterator can also remove the last element produced by next () , which means that the next () method must be called before remove () is called.

It is a powerful idea to accept an object container and pass it on to perform operations on each object.

listlterator is a more powerful subtype of iterator that can only be used for access to a variety of list classes . Although the iterator can only move forward, Listlterator can move in both directions. It can also produce the index of the previous and subsequent elements relative to the current position that the selector points to in the list, and you can use the set () method to replace the last element that it accesses. You can generate a listlterator that points to the beginning of the list by calling the Listlterator() method. You can also create a listlterator at the beginning of an element that points to a list index of n by calling the Listlterator (n) method.

(1) Foreach Traversal Collection Element
1  Public classForeachdemo {2 3 /** 4 * @param args 5 * *6  Public Static voidMain (string[] args) {7 8 /* 9 * JDK1.5 features  : * Enhanced for loop. Function: Used to traverse the collection set or array. * Format: *  for (element type variable: Collection container or array) * *  {+ *  } *     16< /c8> * What is the difference between a traditional for loop and an enhanced for loop?  * Enhanced for must have the target traversed. The target can only be an Collectionor array. * *  *   -  +Collection coll =NewArrayList (); A  atColl.add ("ABC1"); -Coll.add ("ABC2"); -Coll.add ("ABC3"); -  -  for(Object Obj:coll) { -System.out.println (obj); in} - /  * for (Iterator it = Coll.iterator (); It.hasnext ();) {  Object obj = It.next ();  System.out.println (obj); }*/    $ //For array traversal, if you do not manipulate its corner label, you can use the enhanced for if you want to manipulate the corner label. Use Legacy for. Panax Notoginseng int[] arr = {23,15,32,78}; -  for(intX:arr) { theSystem.out.println ("x="+x); +} A  the  +} -  $}
(2) Listiterator traversal list element
1  Public classListiteratordemo {2 3 /** 4 * @param args 5 * *6  Public Static voidMain (string[] args) {7 8List List =NewArrayList ();9 TenList.add ("ABC1"); OneList.add ("ABC2"); AList.add ("ABC3"); -List.add ("ABC4"); -  the  - /  * +//During traversal, if traversing to ABC2, add an element haha for (Iterator  it = List.iterator (); It.hasnext ();) {  Object obj = It.next ();//java.util.concurrentmodificationexception/   / The iteration process uses a collection object to manipulate the element at the same time. Leads to the uncertainty of the iteration. The exception was thrown.  Solution idea: In the iterative process, you want to do something, use the iterator method.   if (obj.equals ("ABC2")) {List.add (  "haha");    /c3> -  in //Use a unique iterator for the list collection. Listiterator gets the iterator object through the method Listiterator () of the list collection.  - //listiterator can be implemented in the iterative process of adding and removing changes.  to  for(Listiterator it = List.listiterator (); It.hasnext ();) { +Object obj = It.next (); -  the if(Obj.equals ("ABC2")){ *It.add ("haha"); $}Panax Notoginseng  -} the  +SYSTEM.OUT.PRINTLN (list); A} the  +}

2018-01-04

Content to autobiographical Intelligence podcast Course

Java Container---iterators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.