Java java지도 시간 Java의 Iterator 인터페이스 및 LIstIterator 인터페이스에 대한 자세한 소개

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

May 28, 2017 am 09:08 AM

이 글에서는 주로 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

자바의 완전수 자바의 완전수 Aug 30, 2024 pm 04:28 PM

Java의 완전수 가이드. 여기서는 정의, Java에서 완전 숫자를 확인하는 방법, 코드 구현 예제에 대해 논의합니다.

자바의 웨카 자바의 웨카 Aug 30, 2024 pm 04:28 PM

Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

Java의 스미스 번호 Java의 스미스 번호 Aug 30, 2024 pm 04:28 PM

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

Java Spring 인터뷰 질문 Java Spring 인터뷰 질문 Aug 30, 2024 pm 04:29 PM

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Feb 07, 2025 pm 12:09 PM

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

Java의 날짜까지의 타임스탬프 Java의 날짜까지의 타임스탬프 Aug 30, 2024 pm 04:28 PM

Java의 TimeStamp to Date 안내. 여기서는 소개와 예제와 함께 Java에서 타임스탬프를 날짜로 변환하는 방법에 대해서도 설명합니다.

캡슐의 양을 찾기위한 Java 프로그램 캡슐의 양을 찾기위한 Java 프로그램 Feb 07, 2025 am 11:37 AM

캡슐은 3 차원 기하학적 그림이며, 양쪽 끝에 실린더와 반구로 구성됩니다. 캡슐의 부피는 실린더의 부피와 양쪽 끝에 반구의 부피를 첨가하여 계산할 수 있습니다. 이 튜토리얼은 다른 방법을 사용하여 Java에서 주어진 캡슐의 부피를 계산하는 방법에 대해 논의합니다. 캡슐 볼륨 공식 캡슐 볼륨에 대한 공식은 다음과 같습니다. 캡슐 부피 = 원통형 볼륨 2 반구 볼륨 안에, R : 반구의 반경. H : 실린더의 높이 (반구 제외). 예 1 입력하다 반경 = 5 단위 높이 = 10 단위 산출 볼륨 = 1570.8 입방 단위 설명하다 공식을 사용하여 볼륨 계산 : 부피 = π × r2 × h (4

Spring Tool Suite에서 첫 번째 Spring Boot 응용 프로그램을 실행하는 방법은 무엇입니까? Spring Tool Suite에서 첫 번째 Spring Boot 응용 프로그램을 실행하는 방법은 무엇입니까? Feb 07, 2025 pm 12:11 PM

Spring Boot는 강력하고 확장 가능하며 생산 가능한 Java 응용 프로그램의 생성을 단순화하여 Java 개발에 혁명을 일으킨다. Spring Ecosystem에 내재 된 "구성에 대한 협약"접근 방식은 수동 설정, Allo를 최소화합니다.

See all articles