Java как работает итератор

Java как работает итератор

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Removes from the underlying collection the last element returned by this iterator (optional operation).

Method Detail

hasNext

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

next

remove

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() . The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

forEachRemaining

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.

 while (hasNext()) action.accept(next()); 

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Interface Iterator

This interface is a member of the Java Collections Framework.

Method Summary

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Removes from the underlying collection the last element returned by this iterator (optional operation).

Method Details

hasNext

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

next

remove

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() . The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy. The behavior of an iterator is unspecified if this method is called after a call to the forEachRemaining method.

Читайте также:  Python графический интерфейс mainloop

forEachRemaining

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller. The behavior of an iterator is unspecified if the action modifies the collection in any way (even by calling the remove method or other mutator methods of Iterator subtypes), unless an overriding class has specified a concurrent modification policy. Subsequent behavior of an iterator is unspecified if the action throws an exception.

 while (hasNext()) action.accept(next()); 

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java как работает итератор

This interface is a member of the Java Collections Framework.

Method Summary

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Removes from the underlying collection the last element returned by this iterator (optional operation).

Method Detail

hasNext

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

next

remove

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() . The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy. The behavior of an iterator is unspecified if this method is called after a call to the forEachRemaining method.

forEachRemaining

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller. The behavior of an iterator is unspecified if the action modifies the collection in any way (even by calling the remove method or other mutator methods of Iterator subtypes), unless an overriding class has specified a concurrent modification policy. Subsequent behavior of an iterator is unspecified if the action throws an exception.

 while (hasNext()) action.accept(next()); 

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Читайте также:  Зарплаты java разработчиков в сбербанке

Источник

Что такое Iterator в Java?

Если вы работаете с числовой программой и говорите, что хотите напечатать последовательность, то здесь входит в работу итератор в Java. Таким образом, вы можете получить последовательность, даже не добавляя оператор печати для каждой строки.

Что такое Iterator в Java?

Iterator в Java – это интерфейс, принадлежащий платформе коллекции. Позволяет просматривать коллекцию, получать доступ к элементу данных и удаляет элементы данных коллекции.

Java в основном поддерживает четыре различных курсора. Это именно:

Каждый из этих Java-курсоров имеет свои преимущества и недостатки.

Он также считается универсальным итератором, так как вы можете применить его к любому объекту Collection. Используя Iterator, вы можете выполнять операции чтения и удаления. Это улучшенная версия перечисления с дополнительными функциями элемента.

Методы Iterator

Итератор Java имеет в общей сложности 4 метода. Давайте разберемся с ними подробно.

Methods Description
forEachRemaining(Consumeraction) Он выполняет действия над каждым элементом до тех пор, пока все элементы не будут обработаны. Также до тех пор, пока действие не создаст исключение.
hasNext() Возвращает истинное значение, если во время итерации встречается большое количество элементов.
next() Возвращает следующий указанный элемент во время итерации.
remove() Этот метод удаляет текущий элемент. Создает исключение IllegalStateException, если предпринята попытка вызвать метод remove(), которому не предшествует вызов метода next().
boolean hasNext() Возвращает true, если итерация содержит больше элементов.
class Method < public static void main(String[] args) ArrayListlist = new ArrayList(); list.add("E"); list.add("D"); list.add("U"); list.add("R"); list.add("E"); list.add("K"); list.add("A"); // Iterator to traverse the list Iterator iterator = list.iterator(); System.out.println("List elements : "); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println(); > >

ListIterator в Java

ListIterator в Java – это итератор, который позволяет пользователям перемещаться по коллекции в обоих направлениях. Он содержит следующие методы:

Читайте также:  Калькулятор исходный код python
Методы Описание
void add(Object obj) Вставляет obj в список перед элементом, который будет возвращен следующим вызовом функции next ().
boolean hasNext( ) Возвращает true, если есть следующий элемент. В противном случае возвращает false.
boolean hasPrevious( ) Возвращает true, если существует предыдущий элемент. В противном случае возвращает false.
Object next( ) Возвращает следующий элемент. Исключение NoSuchElementException создается, если нет следующего элемента.
int nextIndex( ) Возвращает индекс следующего элемента. Если следующего элемента нет, возвращает размер списка.
Object previous( ) Возвращает предыдущий элемент. Исключение NoSuchElementException создается, если предыдущий элемент отсутствует.
int previousIndex( ) Возвращает индекс предыдущего элемента. Если предыдущий элемент отсутствует, то возвращается значение -1.
void remove( ) Удаляет текущий элемент из списка. IllegalStateException бросается, если remove( ) вызывается перед next( ) или previous( ) вызывается.
void set(Object obj) Присваивает obj текущему элементу. Это последний элемент, возвращаемый вызовом функции next() или previous().
public class Lists < public static void main(String args[]) < // Create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("E"); al.add("D"); al.add("U"); al.add("R"); al.add("E"); al.add("K"); al.add("A"); // Use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator(); while(itr.hasNext()) < Object element = itr.next(); System.out.print(element + " "); >System.out.println(); // Modify objects being iterated ListIterator litr = al.listIterator(); while(litr.hasNext()) < Object element = litr.next(); litr.set(element + "+"); >System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) < Object element = itr.next(); System.out.print(element + " "); >System.out.println(); // Now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) < Object element = litr.previous(); System.out.print(element + " "); >System.out.println(); > >

Original contents of al : E D U R E K A
Modified contents of al : E + D + U + R + E + K + A+
Modified list backwards : A + K + E + R + U + D + E+

Преимущества

Итератор в Java имеет следующие преимущества.

  • Вы можете использовать эти итераторы для любого класса Collection.
  • Поддерживает операции чтения и удаления.
  • Если вы используете цикл for, вы не можете обновить (добавить / удалить) коллекцию, тогда как с помощью итератора вы можете легко обновить коллекцию.
  • Универсальный для API коллекции.
  • Имена методов очень просты в использовании.

Ограничения

Имеют следующие недостатки:

  • Вы можете выполнять только итерацию в прямом направлении, то есть однонаправленный итератор.
  • Замена и добавление нового элемента не поддерживается.
  • ListIterator – самый мощный, но он применим только для классов, реализованных в List. Так что это не универсальный итератор.
  • Когда вы используете операции CRUD, он не поддерживает операции создания и обновления.
  • Когда вы сравниваете его со Spliterator, он не позволяет выполнять итерацию элементов параллельно. Это означает, что он поддерживает только последовательную итерацию.
  • Он не поддерживает лучшую производительность для итерации большого объема данных.

Источник

Оцените статью