Java의 Iterator 인터페이스 및 LIstIterator 인터페이스에 대한 자세한 소개
이 글에서는 주로 java Iteratorinterface 및 LIstIterator 인터페이스 분석 관련 정보를 소개합니다. 필요한 친구들은
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 super E> 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'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
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 | |||||||||||||||||||||||||||||||||||
hasNext() | hasNext() | 재정의||||||||||||||||||||||||||||||||||
next()
|
next() | 재정의 | |||||||||||||||||||||||||||||||||
remove() |
remove() | 재정의 | |||||||||||||||||||||||||||||||||
forEachRemaining(소비자< ;? 슈퍼 E> 액션) | forEachRemaining(소비자 슈퍼 E> 액션) | 상속됨 | |||||||||||||||||||||||||||||||||
has이전() | |||||||||||||||||||||||||||||||||||
이전() | |||||||||||||||||||||||||||||||||||
nextIndex() | |||||||||||||||||||||||||||||||||||
previousIndex() | |||||||||||||||||||||||||||||||||||
set(E e) | |||||||||||||||||||||||||||||||||||
add(E e) |
1) .Iterator는 한 방향으로만 이동할 수 있는 반면 ListIterator는 양방향으로 이동할 수 있습니다.
2).ListIterator는 요소를
삭제🎜하고 교체하거나 추가할 수 있는 반면 Iterator는 요소를 삭제할 수만 있습니다. 🎜🎜 3). 현재(next() 호출) 또는 이전()이 반환한 요소의 인덱스를 반환할 수 있지만 Iterator는 반환할 수 없습니다. 🎜위 내용은 Java의 Iterator 인터페이스 및 LIstIterator 인터페이스에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











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

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

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

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

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

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

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