> Java > java지도 시간 > 본문

Java의 Iterator 인터페이스 및 LIstIterator 인터페이스에 대한 자세한 소개

黄舟
풀어 주다: 2017-05-28 09:08:19
원래의
1495명이 탐색했습니다.

이 글에서는 주로 java IteratorinterfaceLIstIterator 인터페이스 분석 관련 정보를 소개합니다. 필요한 친구들은

java Iterator 인터페이스 및 LIstIterator 인터페이스 분석

목차

를 참고하세요.

1 .Iterator 인터페이스
2. ListIterator
3. Iterator와 ListIterator의 차이점

텍스트

ArrayList 소스 코드를 계속 살펴보기 전에 먼저 Iterator 인터페이스와 ListIterator 인터페이스를 이해하세요. ArrayList가 이를 구현하는 방법을 자세히 설명합니다.

우리는 인터페이스가 단지 사양일 뿐이라는 것을 알고 있습니다. 인터페이스를 상속 하고 해당 메서드를 구현할 때는 인터페이스의 메서드 설명을 따라야 합니다.

1.Iterator 인터페이스

Iterator 인터페이스는 Java 컬렉션 프레임워크 의 Enumeratrion을 대체합니다. 반복자는 두 가지 주요 측면에서 열거형과 다릅니다.

 반복자는 호출자가 반복 프로세스 중에 컬렉션에서 요소를 제거할 수 있도록 합니다.

 메서드 이름이 개선되었습니다.

Iterator 소스 코드는 다음과 같습니다.

/**
 * An iterator over a collection. {@code Iterator} takes the place of
 * {@link Enumeration} in the Java Collections Framework. Iterators
 * differ from enumerations in two ways:
 * Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
 * Method names have been improved.
 * This interface is a member of the Java Collections Framework.
 * @param <E> the type of elements returned by this iterator*/
public interface Iterator<E> {
  /**
   * Returns {@code true} if the iteration has more elements.
   * (In other words, returns {@code true} if {@link #next} would
   * return an element rather than throwing an exception.)
   * @return {@code true} if the iteration has more elements
   */
  boolean hasNext();

  /**
   * Returns the next element in the iteration.
   * @return the next element in the iteration
   * @throws NoSuchElementException if the iteration has no more elements
   */
  E next();

  /**
   * Removes from the underlying collection the last element returned
   * by this iterator (optional operation). This method can be called
   * only once per call to {@link #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.
   *
   * @implSpec
   * The default implementation throws an instance of
   * {@link UnsupportedOperationException} and performs no other action.
   *
   * @throws UnsupportedOperationException if the {@code remove}
   *     operation is not supported by this iterator
   *
   * @throws IllegalStateException if the {@code next} method has not
   *     yet been called, or the {@code remove} method has already
   *     been called after the last call to the {@code next}
   *     method
   */
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }

  /**
   * 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.
   *
   * @implSpec
   * <p>The default implementation behaves as if:
   * <pre class="brush:php;toolbar:false">{@code
   *   while (hasNext())
   *     action.accept(next());
   * }
* * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null * @since 1.8 */ default void forEachRemaining(Consumer action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
로그인 후 복사

Iterator 인터페이스는 네 가지 메소드와 각 메소드의 기능을 정의합니다. 클래스가 이 인터페이스를 구현하고 이러한 메소드를 구현하는 경우 이 메소드는 정의된 기능을 구현하고 다음 규칙을 따라야 합니다.

 1).hasNext()는 컨테이너에 다음 요소가 있는지 확인하고, 그렇다면 true를 반환합니다.

 2).next()는 컨테이너의 다음 요소를 반환합니다.

 3).remove()는 현재 요소를 제거합니다. iterator 반환된 마지막 요소입니다. 이 메서드는 next() 메서드를 호출할 때마다 한 번만 호출할 수 있습니다.

 4) Java 8은 나머지 모든 요소에 대해 지정된 작업을 수행할 수 있는 forEachRemaning 메서드를 추가합니다.

자세한 지침은 소스 코드의 설명을 읽어보세요.

2. ListIterator

ListIterator는 Iterator를 기반으로 add, set, previous 및 기타 목록 작업을 제공합니다. 그러나 ListIterator는 Iterator와 마찬가지로 여전히 원래 목록에서 작동합니다.

ListIterator 소스 코드는 다음과 같습니다.

/**
 * An iterator for lists that allows the programmer
 * to traverse the list in either direction, modify
 * the list during iteration, and obtain the iterator&#39;s
 * current position in the list. A {@code ListIterator}
 * has no current element; its <I>cursor position</I> always
 * lies between the element that would be returned by a call
 * to {@code previous()} and the element that would be
 * returned by a call to {@code next()}.
 * An iterator for a list of length {@code n} has {@code n+1} possible
 * cursor positions, as illustrated by the carets ({@code ^}) below:
 * <PRE>
 *           Element(0)  Element(1)  Element(2)  ... Element(n-1)
 * cursor positions: ^      ^      ^      ^         ^
 * 
* Note that the {@link #remove} and {@link #set(Object)} methods are * not defined in terms of the cursor position; they are defined to * operate on the last element returned by a call to {@link #next} or * {@link #previous()}. * * This interface is a member of the Java Collections Framework.*/ public interface ListIterator extends Iterator { // Query Operations /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the forward direction. (In other words, * returns {@code true} if {@link #next} would return an element rather * than throwing an exception.) * * @return {@code true} if the list iterator has more elements when * traversing the list in the forward direction */ boolean hasNext(); /** * Returns the next element in the list and advances the cursor position. * This method may be called repeatedly to iterate through the list, * or intermixed with calls to {@link #previous} to go back and forth. * (Note that alternating calls to {@code next} and {@code previous} * will return the same element repeatedly.) * * @return the next element in the list * @throws NoSuchElementException if the iteration has no next element */ E next(); /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the reverse direction. (In other words, * returns {@code true} if {@link #previous} would return an element * rather than throwing an exception.) * * @return {@code true} if the list iterator has more elements when * traversing the list in the reverse direction */ boolean hasPrevious(); /** * Returns the previous element in the list and moves the cursor * position backwards. This method may be called repeatedly to * iterate through the list backwards, or intermixed with calls to * {@link #next} to go back and forth. (Note that alternating calls * to {@code next} and {@code previous} will return the same * element repeatedly.) * * @return the previous element in the list * @throws NoSuchElementException if the iteration has no previous * element */ E previous(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #next}. (Returns list size if the list * iterator is at the end of the list.) * * @return the index of the element that would be returned by a * subsequent call to {@code next}, or list size if the list * iterator is at the end of the list */ int nextIndex(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #previous}. (Returns -1 if the list * iterator is at the beginning of the list.) * * @return the index of the element that would be returned by a * subsequent call to {@code previous}, or -1 if the list * iterator is at the beginning of the list */ int previousIndex(); // Modification Operations /** * Removes from the list the last element that was returned by {@link * #next} or {@link #previous} (optional operation). This call can * only be made once per call to {@code next} or {@code previous}. * It can be made only if {@link #add} has not been * called after the last call to {@code next} or {@code previous}. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this list iterator * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void remove(); /** * Replaces the last element returned by {@link #next} or * {@link #previous} with the specified element (optional operation). * This call can be made only if neither {@link #remove} nor {@link * #add} have been called after the last call to {@code next} or * {@code previous}. * * @param e the element with which to replace the last element returned by * {@code next} or {@code previous} * @throws UnsupportedOperationException if the {@code set} operation * is not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void set(E e); /** * Inserts the specified element into the list (optional operation). * The element is inserted immediately before the element that * would be returned by {@link #next}, if any, and after the element * that would be returned by {@link #previous}, if any. (If the * list contains no elements, the new element becomes the sole element * on the list.) The new element is inserted before the implicit * cursor: a subsequent call to {@code next} would be unaffected, and a * subsequent call to {@code previous} would return the new element. * (This call increases by one the value that would be returned by a * call to {@code nextIndex} or {@code previousIndex}.) * * @param e the element to insert * @throws UnsupportedOperationException if the {@code add} method is * not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of this element * prevents it from being added to this list */ void add(E e); }
로그인 후 복사

ListIterator가 더 강력하며 정의된 메서드는 다음과 같습니다.

 1).hasNext() 앞으로 순회할 때 다음 요소가 있으면 true를 반환합니다. 2).next( ) 다음 요소의 값을 반환하고 포인터에 1을 추가합니다.

 3).hasPrevious() 반대 방향으로 이동할 때 여전히 요소가 있으면 true를 반환합니다.

 4). 이전() 이전 요소의 값을 반환하고 포인터를 1만큼 앞으로 이동합니다.

 5).nextIndex()는 이때 next() 메서드가 호출될 때 반환된 요소의

index를 반환합니다. ).previousIndex()는 이때 이전() 메서드가 호출될 때 반환되는 내용을 반환합니다. 요소의 인덱스

 7).remove()는 next() 또는 이전()에 대한 가장 최근 호출에서 반환된 요소를 제거합니다. ) 메서드(선택 사항);

 8).set(E e) 다음() 또는 이전() 메서드를 호출하여 반환된 요소를 교체하려면 e 요소를 사용합니다. 이때 next()를 호출하여 반환된 요소 앞의 요소 또는 이후에 이전()을 호출하여 반환된 요소입니다.

자세한 지침은 소스 코드의 주석을 읽어보세요.

3 Iterator와 ListIterator의 차이점

Iterator와 ListIterator의 메서드를 다음 표에서 비교합니다.

재정의

Iterator

ListIterator
hasNext()

hasNext()
next()

Iterator

ListIterator

 

hasNext()

hasNext() 覆盖

next()

next() 覆盖

remove()

remove() 覆盖

forEachRemaining(Consumer action)

forEachRemaining(Consumer action) 继承
  hasPrevious()  
  previous()  
  nextIndex()  
  previousIndex()  
  set(E e)  
  add(E e)  
next() 재정의

remove()

remove() 재정의
forEachRemaining(소비자< ;? 슈퍼 E> 액션) forEachRemaining(소비자 액션) 상속됨
has이전()
이전()
nextIndex()
previousIndex()
set(E e)
add(E e)

둘 사이의 주요 차이점은 다음과 같습니다.

 1) .Iterator는 한 방향으로만 이동할 수 있는 반면 ListIterator는 양방향으로 이동할 수 있습니다.

 2).ListIterator는 요소를

삭제🎜하고 교체하거나 추가할 수 있는 반면 Iterator는 요소를 삭제할 수만 있습니다. 🎜🎜 3). 현재(next() 호출) 또는 이전()이 반환한 요소의 인덱스를 반환할 수 있지만 Iterator는 반환할 수 없습니다. 🎜

위 내용은 Java의 Iterator 인터페이스 및 LIstIterator 인터페이스에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!