- Java — How to Use Iterator?
- The Methods Declared by Iterator
- The Methods Declared by ListIterator
- Example
- Java Iterator with examples
- Iterator without Generics Example
- Iterator with Generics Example
- Difference between Iterator and Enumeration
- ConcurrentModificationException while using Iterator
- Java Iterator
- Java Iterator
- Getting an Iterator
- Example
- Looping Through a Collection
- Example
- Removing Items from a Collection
- Example
- COLOR PICKER
- CODE GAME
- Report Error
- Thank You For Helping Us!
- Android what is iterator
- Methods of Iterator
- Types of Iterators
- How to Iterate Over Elements
- Why use Iterator when we have Enumerator
- 30.21. Java – Iterator и ListIterator
- Содержание
- Методы, объявленные Iterator
- Методы, объявленные ListIterator
- Пример
Java — How to Use Iterator?
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps −
Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling ListIterator.
The Methods Declared by Iterator
Returns true if there are more elements. Otherwise, returns false.
Returns the next element. Throws NoSuchElementException if there is not a next element.
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
The Methods Declared by ListIterator
void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
Returns true if there is a next element. Otherwise, returns false.
Returns true if there is a previous element. Otherwise, returns false.
Returns the next element. A NoSuchElementException is thrown if there is not a next element.
Returns the index of the next element. If there is not a next element, returns the size of the list.
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
Returns the index of the previous element. If there is not a previous element, returns -1.
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).
Example
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.
Of course, ListIterator is available only to those collections that implement the List interface.
Источник
Java Iterator with examples
By Chaitanya Singh | Filed Under: Java Collections
Iterator is used for iterating (looping) various collection classes such as HashMap, ArrayList, LinkedList etc. In this tutorial, we will learn what is iterator, how to use it and what are the issues that can come up while using it. Iterator took place of Enumeration, which was used to iterate legacy classes such as Vector. We will also see the differences between Iterator and Enumeration in this tutorial.
Iterator without Generics Example
Generics got introduced in Java 5. Before that there were no concept of Generics.
In the above example we have iterated ArrayList without using Generics. Program ran fine without any issues, however there may be a possibility of ClassCastException if you don’t use Generics (we will see this in next section).
Iterator with Generics Example
In the above section we discussed about ClassCastException. Lets see what is it and why it occurs when we don’t use Generics.
In the above program we tried to add Integer value to the ArrayList of String but we didn’t get any compile time error because we didn’t use Generics. However since we type casted the integer value to String in the while loop, we got ClassCastException.
Use Generics:
Here we are using Generics so we didn’t type caste the output. If you try to add a integer value to ArrayList in the below program, you would get compile time error. This way we can avoid ClassCastException.
Note: We did not type cast iterator returned value[it.next()] as it is not required when using Generics.
Difference between Iterator and Enumeration
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
1) Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
2) Method names have been improved. hashNext() method of iterator replaced hasMoreElements() method of enumeration, similarly next() replaced nextElement().
ConcurrentModificationException while using Iterator
We cannot add or remove elements to the collection while using iterator over it.
Explanation From Javadoc:
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Источник
Java Iterator
Java Iterator
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an «iterator» because «iterating» is the technical term for looping.
To use an Iterator, you must import it from the java.util package.
Getting an Iterator
The iterator() method can be used to get an Iterator for any collection:
Example
Looping Through a Collection
To loop through a collection, use the hasNext() and next() methods of the Iterator :
Example
Removing Items from a Collection
Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping.
Example
Use an iterator to remove numbers less than 10 from a collection:
Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.
We just launched
W3Schools videos
COLOR PICKER
Get certified
by completing
a course today!
CODE GAME
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Web Courses
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Источник
Android what is iterator
There are different ways by which we can traverse over elements that are for-loop, while loop, do-while, for each loop etc. They all are index based on traversing methods. But as we know Java is purely object oriented programming language in which we always have possible ways of doing things using objects. So Iterator is a way to traverse the data over the collection objects.
Java Iterator is an Interface that belongs to the collection framework allow us to traverse the collection objects and access the elements of that collection. Basically List Interface and Set Interface provides the iterator. Iterator can be used with all the implementation of Set and List Interfaces like for example ArrayList, LinkedList, TreeSet etc.
Map implementation such as HashMap, TreeMap, LinkedHashMap doesn’t provide Iterator directly but we can iterate over them by getting there key-Set or Value Set.
Table of Contents
Methods of Iterator
1. boolean hasNext( )
This method returns true if there are more elements else it returns false.
2. Object next( )
This method returns the next element in the collection or else throws NoSuchElementException if there is no next element present.
3. void remove( )
This method removes the current element on which iteretor points to or else throws IllegalStateException if remove( ) method is called that is not preceded by a call to next( ) method.
Types of Iterators
1. fail-fast Iterator
As name suggests fail-fast Iterator fails as soon as the structure of Collection has been changed since traversing has begun. Changes means adding, removing or updating any element from collection while one thread is Iterating over that collection.
fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.
2. fail-safe Iterator
Contrary to fail-fast Iterator, fail-safe iterator doesn’t throw any Exception if Collection is modified structurally while one thread is traversing over it as they work on copy of Collection instead of original collection and that is why, they are called as fail-safe iterator.
How to Iterate Over Elements
Every collection class has an iterator() method which returns an iterator object to the beginning of the collection elements. By using this object, we can access each element in the collection and each element at a time.
To use an Iterator to traverse the collection follow these steps:
1. Obtain an Iterator by calling the collection’s iterator( ) method.
2. Create a loop that makes a call to hasNext( ) method.
3. Iterate the loop as long as hasNext() method returns true.
4. In the loop get each element by calling next( ) method.
Example of How to use Iterator with List Interface in Java:
Let us discuss Iterator with List Interface with the help of program, following program has been divided into 3 Steps that we will discuss one by one:
Output:
Description:
- In Step 1, we have created an object of List Interface that is of String type.
- In Step 2, we have used add method to add values in the data structure that we have created in step 1.
- In Step 3, we have created an object of Iterator of type String.
- In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.
Example of How to use Iterator with Set Interface in Java:
Let us discuss Iterator with Set Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one.
Output:
Description:
- In Step 1, we have created an object of Set Interface that is of String type.
- In Step 2, we have used add method to add values in the data structure that we have created in step 1.
- In Step 3, we have created an object of Iterator of type String.
- In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.
Example of How to use Iterator with Map Interface in Java:
Iterating over any of the Map implementations like Hashmap, TreeMap etc is not very straight forward as compared to other collections. Let us discuss Iterator with Map Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one
Output:
Description:
- In Step 1, we have created an object of HashMap class, as we know HashMap has key value pair, so we have defined Key of Integer type, and Value of String type.
- In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
- In Step 3, we have created object of Iterator class, that will be used to further traverse the map.
- In Step 4 weh have used while loop, that has used hasNext() method that tell whether there is next element present or not, and next() method that gives the next element during traversing. And we have used two more methods , First is getKey() , which as name suggest retrieves the key and secondly getValue() method that retrieves the values corresponding to the keys.
Why use Iterator when we have Enumerator
Both Iterator and Enumerator is used for traversing the collection, then why we need Iterator? Following points will tell why we need Iterator:
- Iterator is more enhanced as extra method remove () is provided by which we can modify the collection which is not available in Enumeration .
- Iterator is more secure as it doesn’t allow another thread to modify the collection when some another thread is traversing the collection and throwsconcurrentModificationException.
- Along with above benefits names of methods defined in Iterator are also very convenient which is not major difference but make use of iterator more easy.
Источник
30.21. Java – Iterator и ListIterator
Часто вам нужно циклически перемещаться по элементам в коллекции. Например, вы можете отобразить каждый элемент. Самый простой способ сделать это — использовать итератор, который является объектом, который реализует интерфейс Iterator или ListIterator.
Содержание
Итератор позволяет вам перемещаться по коллекции, получать или удалять элементы. ListIterator расширяет Итератор, чтобы обеспечить двунаправленный обход списка и модификацию элементов.
Прежде чем вы сможете получить доступ к коллекции через итератор, вы должны ее получить. Каждый из классов коллекции предоставляет метод iterator (), который возвращает итератор в начало коллекции. Используя этот объект итератора, вы можете получить доступ к каждому элементу в коллекции, по одному элементу за раз.
В общем случае, чтобы использовать итератор для циклического перемещения содержимого коллекции, выполните следующие действия:
- Получите итератор в начале коллекции, вызвав метод iterator() коллекции.
- Настройте цикл, который вызывает hasNext(). Повторяйте цикл, пока hasNext() возвращает true.
- Внутри цикла получите каждый элемент, вызывая next().
Для коллекций, которые реализуют List, вы также можете получить итератор, вызвав ListIterator.
Методы, объявленные Iterator
№ | Метод и описание |
1 | boolean hasNext( ) Возвращает true, если есть ещё элементы. В противном случае возвращает false. |
2 | Object next( ) Возвращает следующий элемент. Вызывает исключение NoSuchElementException, если не существует следующего элемента. |
3 | void remove( ) Удаляет текущий элемент. Выбрасывает IllegalStateException, если делается попытка вызвать remove(), которому не предшествует вызов next(). |
Методы, объявленные ListIterator
№ | Метод и описание |
1 | void add(Object obj) Вставляет obj в список перед элементом, который будет возвращен следующим вызовом next(). |
2 | boolean hasNext( ) Возвращает true, если есть следующий элемент. В противном случае возвращает false. |
3 | boolean hasPrevious( ) Возвращает true, если есть предыдущий элемент. В противном случае возвращает false. |
4 | Object next( ) Возвращает следующий элемент. A NoSuchElementException вызывается, если не существует следующего элемента. |
5 | int nextIndex( ) Возвращает индекс следующего элемента. Если нет следующего элемента, возвращается размер списка. |
6 | Object previous( ) Возвращает предыдущий элемент. A NoSuchElementException вызывается, если не существует следующего элемента. |
7 | int previousIndex( ) Возвращает индекс предыдущего элемента. Если нет предыдущего элемента, возвращается -1. |
8 | void remove( ) Удаляет текущий элемент из списка. Вызывается IllegalStateException, если вызывается функция remove() вызвана перед next() или previous(). |
9 | void set(Object obj) Назначает obj текущему элементу. Это последний элемент, возвращаемый вызовом либо next(), либо previous(). |
Пример
Вот пример, демонстрирующий как Iterator, так и ListIterator в Java. Он использует объект ArrayList, но общие принципы применимы к любому типу коллекции.
Конечно, ListIterator доступен только для тех коллекций, которые реализуют интерфейс List.
Источник