- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterators In Java
Iterators are used to traverse through the Java collections. There are three types of iterators.
Enumeration − Enumeration is initial iterators introduced in jdk 1.0 and is only for older collections like vector or hashTables. Enumeration can be used for forward navigation only. Element can not be removed using Enumeration.
Iterator − Iterator is a universal iterator introduced in Jdk 1.2 and can be used for any collections. Iterator can b e used for forward navigation only. Element can be removed using iterator if remove method is supported.
ListIterator − ListIterator is a iterator for List type collections and supports bidirectional navigation.
Example
import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Vector; public class Tester{ public static void main(String[] args) throws ClassNotFoundException { Vector<Integer> vector = new Vector<>(); vector.add(1);vector.add(2);vector.add(3); System.out.println("Vector: "); Enumeration<Integer> enumeration = vector.elements(); while(enumeration.hasMoreElements()){ System.out.print(enumeration.nextElement() + " "); } List<Integer> list = new ArrayList<Integer>(); list.add(1);list.add(2);list.add(3); System.out.println("
List: "); Iterator<Integer> iterator = list.iterator(); while(iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println("
List using ListItertor (Forward): "); ListIterator<Integer> listIterator = list.listIterator(); while(listIterator.hasNext()){ System.out.print(listIterator.next() + " "); } System.out.println("
List using ListItertor (Backward): "); while(listIterator.hasPrevious()){ System.out.print(listIterator.previous() + " "); } } }
Output
Vector: 1 2 3 List: 1 2 3 List using ListItertor (Forward): 1 2 3 List using ListItertor (Backward): 3 2 1
Advertisements