Você está na página 1de 5

Iterators

The List and Set collections provide iterators, which are objects that allow going over all the elements of a collection in sequence. The java.util.Iterator<E>interface provides for one-way traversal and java.util.ListIterator<E>provides two-way traversal. Iterator<E> is a replacement for the olderEnumeration class which was used before collections were added to Java.

Creating an Iterator
Iterators are created by calling the iterator() or listIterator()method of a List, Set, or other data collection with iterators.

Iterator Methods
Iterator defines three methods, one of which is optional. Result Method Description Returns the next object. If a generic list is being accessed, the iterator will return something of the list's type. Pre-generic Java iterators always returned type Object, so a downcast was usually required. it.remove() Removes the most recent element that was returned by next. Not all collections support delete. An UnsupportedOperationException will be thrown if the collection does not support remove().

b = it.hasNext() true if there are more elements for the iterator. obj = it.next()

Example with Java 5 generics


An iterator might be used as follows. ArrayList<String> alist = new ArrayList<String>(); // . . . Add Strings to alist

for (Iterator<String> it = alist.iterator(); it.hasNext(); ) { String s = it.next(); System.out.println(s); } // No downcasting required.

Example as above but with enhanced Java 5 for loop


for (String s : alist) { System.out.println(s); }

Example pre Java 5, with explicit iterator and downcasting


An iterator might be used as follows, wi. ArrayList alist = new ArrayList(); // This holds type Object. // . . . Add Strings to alist

for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = (String)it.next(); System.out.println(s); } // Downcasting is required pre Java 5.

ListIterator methods
ListIterator is implemented only by the classes that implement the List interface (ArrayList, LinkedList, and Vector). ListIterator provides the following. Result Method Description true if there is a next element in the collection. Returns the next object. true if there is a previous element. Returns the previous element. Returns index of element that would be returned by subsequent call to next().

Forward iteration b = it.hasNext() obj = it.next() Backward iteration b = it.hasPrevious() obj = it.previous()

Getting the index of an element i = it.nextIndex()

i = it.previousIndex() Returns index of element that would be returned by subsequent call to previous(). Optional modification methods. UnsupportedOperationException thrown if unsupported. it.add(obj) Inserts obj in collection before the next element to be returned by next() and after an element that would be returned by previous(). Replaces the most recent element that was returned by next or previous(). Removes the most recent element that was returned by next() or previous().

it.set() it.remove()

The iterator interface with ArrayList

Iterator is an interface in the collection framework. ArrayList is a collection class and implements the List Inteface. All the elements of the ArrayList can be traversed by the Iterator. Iterator has methods hasNext() and next().

Example of Java Arraylist Iterate


import java.util.*; public class javaarray { public static void main(String[] args) { List list = new ArrayList(); list.add("aaaa"); list.add("bbbb"); list.add("cccc"); list.add("dddd"); Iterator i = list.iterator(); while (i.hasNext()) { System.out.print(i.next() + "\t"); } } }

Output aaaa bbbb cccc dddd

The iterator interface with Collection


The Java Collection Iterator is present at the highest level interface in the Collection framework. Iterator interface has methods for traversing, but Collection doesn't has iterator() method. So create object with reference to other collection class.Those class should have iterator() method.

Example of Java Collection Iterator


import import import public java.util.ArrayList; java.util.Collection; java.util.Iterator; class collection2 { public static void main(String[] args) { Collection c = new ArrayList(); c.add("rose"); c.add("Lotus"); c.add("Marigold"); c.add("Jasmine"); Iterator ir = c.iterator(); while (ir.hasNext()) { System.out.println(ir.next()); } } }

Output: rose Lotus Marigold Jasmine

The iterator interface with HashMap

Java HashMap Iterator is an interface. It keeps the data in the key and value form.

It is implemented by HashMap. hashMap doesnot have iterator method. So use the entrySet() method to get the data in Set object form. Set's all elements can be traversed by the Iterator.

Example of Java HashMap Iterator


import java.util.*; public class hashmap { public static void main(String[] args) { HashMap hash = new HashMap(); hash.put("roll", new Integer(12)); hash.put("name", "jack"); hash.put("age", 22); Set s = hash.entrySet(); Iterator i = s.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }

Output roll=12 age=22 name=jack

The iterator interface and its functionality


Iterator is an interface in the collection framework It traverses through all the elements of the collection. It works like enumeration. It has methods hasNext() and next().

Java Iterator Example


import java.util.*; public class iterator { public static void main(String[] args) { List list=new ArrayList(); for (int i = 0; i <5 ; i++) { list.add(new Random().nextInt(10)); } Iterator i=list.iterator(); while(i.hasNext()){ System.out.print(i.next()+"\t"); } } }

Output 63753

The iterator interface with List


Java List Iterator is an interface in the collection framework. List is an interface. Its all elements can be traversed by the Iterator. Java List Iterator has methods hasNext() and next() for traversing .

Java List Iterator Example

import java.util.*;public class list { public static void main(String[] args) { List l = new ArrayList(); for (int i = 1; i < 6; i++) { l.add(i); } Iterator it = l.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }

Output : 12345
A Software Pattern is: A solution To a problem In a context With consequences A Software Pattern has a name and a vocabulary. Pattern Languages Intent Also Known As Motivation Applicability Structure Participants Collaborations Consequences Implementation Known Uses Related Patterns Intent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation

Você também pode gostar