What is an iterator interface in java

What is an iterator interface in 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.

Читайте также:  Bar charts in java

Источник

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.

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.

Источник

Паттерн Iterator

Java-университет

Как ты уже, вероятно, знаешь, в Java есть замечательный интерфейс Collection, реализующий интерфейс Iterator. Сразу оговорюсь, не следует путать интерфейс iterator с паттерном iterator в Java! И дабы внести ясность, для начала разберёмся именно с интерфейсом.

Дословно «Iterator» можно перевести как «переборщик». То есть это некая сущность, способная перебрать все элементы в коллекции. При этом она позволяет это сделать без вникания во внутреннюю структуру и устройство коллекций.

Представим на секунду, что iterator в Java отсутствует. В таком случае всем и каждому придётся нырнуть в самые глубины коллекций и по-настоящему разобраться, чем отличается, ArrayList от LinkedList и HashSet от TreeSet .

Методы, которые должен имплементировать Iterator

  • UnsupportedOperationException , если данный итератор не поддерживает метод remove() (в случае с read-only коллекциями, например)
  • IllegalStateException , если метод next() еще не был вызван, или если remove() уже был вызван после последнего вызова next() .
  • void add(E e) — вставляет элемент E в List ;
  • boolean hasPrevious() — вернет true , если при обратном переборе List имеются элементы;
  • int nextIndex() — вернет индекс следующего элемента;
  • E previous() — вернет предыдущий элемент листа;
  • int previousIndex() — вернет индекс предыдущего элемента;
  • void set(E e) — заменит элемент, возвращенный последним вызовом next() или previous() на элемент e .
 List list = new ArrayList<>(); list.add("Привет"); list.add("Обучающимся"); list.add("На"); list.add("JavaRush"); 
 Iterator iterator = list.iterator(); while (iterator.hasNext())

Сейчас будет «узкое место»: Java Collections как ты, вероятно, знаешь (а если не знаешь, разберись), расширяют интерфейс Iterable , но это не означает, что только List , Set и Queue поддерживают итератор. Для java Map iterator также поддерживается, но его необходимо вызывать для Map.entrySet() :

 Map map = new HashMap<>(); Iterator mapIterator = map.entrySet().iterator(); 

Тогда метод next() будет возвращать объект Entry , содержащий в себе пару «ключ»-«значение». Дальше все аналогично с List :

 while (mapIterator.hasNext()) < Map.Entryentry = mapIterator.next(); System.out.println("Key: " + entry.getKey()); System.out.println("Value: " + entry.getValue()); > 

Ты думаешь: «Стоп. Мы говорим про интерфейс, а в заголовке статьи написано «Паттерн». То есть, паттерн iterator – это интерфейс Iterator? Или интерфейс — это паттерн?» Если это слово встречается впервые, даю справку: паттерн — это шаблон проектирования, некое поведение, которого должен придерживаться класс или множество взаимосвязанных классов. Итератор в java может быть реализован для любого объекта, внутренняя структура которого подразумевает перебор, при этом можно изменить сигнатуру обсуждаемых методов. Главное при реализации паттерна – логика, которой должен придерживаться класс. Интерфейс итератор – частная реализация одноименного паттерна, применяемая как к готовым структурам ( List, Set, Queue, Map ), так и к прочим, на усмотрение программиста. Расширяя интерфейс Iterator, ты реализуешь паттерн, но для реализации паттерна не обязательно расширять интерфейс. Простая аналогия: все рыбы плавают, но не всё, что плавает – рыбы. В качестве примера я решил взять… слово. А конкретнее — существительное. Оно состоит из частей: приставки, корня, суффикса и окончания. Для частей слова создадим интерфейс WordPart и классы, расширяющие его: Prefix, Root, Suffix и Ending :

 interface WordPart < String getWordPart(); >static class Root implements WordPart < private String part; public Root(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Prefix implements WordPart < private String part; public Prefix(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Suffix implements WordPart < private String part; public Suffix(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Ending implements WordPart < private String part; public Ending(String part) < this.part = part; >@Override public String getWordPart() < return part; >> 

Тогда класс Word (слово) будет содержать в себе части, а кроме них добавим целое число, отражающее количество частей в слове:

 public class Word < private Root root; private Prefix prefix; private Suffix suffix; private Ending ending; private int partCount; public Word(Root root, Prefix prefix, Suffix suffix, Ending ending) < this.root = root; this.prefix = prefix; this.suffix = suffix; this.ending = ending; this.partCount = 4; >public Word(Root root, Prefix prefix, Suffix suffix) < this.root = root; this.prefix = prefix; this.suffix = suffix; this.partCount = 3; >public Word(Root root, Prefix prefix) < this.root = root; this.prefix = prefix; this.partCount = 2; >public Word(Root root) < this.root = root; this.partCount = 1; >public Root getRoot() < return root; >public Prefix getPrefix() < return prefix; >public Suffix getSuffix() < return suffix; >public Ending getEnding() < return ending; >public int getPartCount() < return partCount; >public boolean hasRoot() < return this.root != null; >public boolean hasPrefix() < return this.prefix != null; >public boolean hasSuffix() < return this.suffix != null; >public boolean hasEnding()

Окей, у нас есть четыре перегруженных конструктора (для простоты, предположим, что суффикс у нас может быть только один). Существительное не может состоять из одной приставки, поэтому для конструктора с одним параметром будем устанавливать корень. Теперь напишем реализацию паттерна итератор: WordIterator, переопределяющий 2 метода: hasNext() и next() :

 public class WordIterator implements Iterator  < private Word word; private int wordPartsCount; public WordIterator(Word word) < this.word = word; this.wordPartsCount = word.getPartCount(); >@Override public boolean hasNext() < if (wordPartsCount == 4) < return word.hasPrefix() || word.hasRoot() || word.hasSuffix() || word.hasEnding(); >else if (wordPartsCount == 3) < return word.hasPrefix() || word.hasRoot() || word.hasSuffix(); >else if (wordPartsCount == 2) < return word.hasPrefix() || word.hasRoot(); >else if (wordPartsCount == 1) < return word.hasRoot(); >return false; > @Override public Word.WordPart next() throws NoSuchElementException < if (wordPartsCount try < if (wordPartsCount == 4) < return word.getEnding(); >if (wordPartsCount == 3) < return word.getSuffix(); >if (wordPartsCount == 2) < return word.getPrefix(); >return word.getRoot(); > finally < wordPartsCount--; >> > 
 public class Word implements Iterable < … @Override public Iteratoriterator() < return new WordIterator(this); >… > 

Источник

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