> Java > java지도 시간 > 본문

Java의 반복자

王林
풀어 주다: 2024-08-30 15:11:37
원래의
311명이 탐색했습니다.

Iterator는 컬렉션의 요소를 하나씩 가져오는 데 사용되는 인터페이스입니다. Java라는 Java 패키지에서 사용할 수 있습니다. 유틸리티 패키지. 컬렉션 API는 iterator() 메서드를 구현하므로 컬렉션 프레임워크에서 모두 구현되는 Map, List, Queue, Deque 및 Set와 같은 인터페이스에서 데이터를 검색할 수 있습니다. 이름에서 알 수 있듯이 Java의 반복자는 객체 컬렉션을 반복합니다.

구문:

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Iterator<E> iterator()
로그인 후 복사

iterator 아래에는 컬렉션 인터페이스의 iterator() 메소드를 호출하여 생성된 객체의 이름이 있습니다. "컬렉션"은 컬렉션 개체의 이름입니다.

Iterator iter = collection.iterator();
로그인 후 복사

Java의 Iterator 메서드

반복자에는 컬렉션을 탐색하고 필요한 정보를 검색하는 데 사용되는 Java의 4가지 메소드가 있습니다. 그 내용은 다음과 같습니다.

  • hasNext(): 반복에 다음 요소가 있으면 부울 true를 반환하고 다음에 요소가 없으면 부울 false를 반환하는 메서드입니다.
  • next (): 이 메소드는 다음 반복에 존재하는 요소 값을 반환합니다. 다음 반복에서 요소가 반환되지 않으면 "NoSuchElementException"이 발생한다고 가정합니다.
  • remove(): 이 메서드는 반복자가 반환한 현재 요소를 컬렉션에서 제거합니다. 이 메소드가 next() 메소드보다 먼저 호출되면 “IllegalStateException”이 발생합니다.
  • forEachRemaining(): 이 메서드는 처리가 완료되거나 예외가 발생할 때까지 컬렉션의 나머지 모든 요소를 ​​실행합니다. 또한 이는 Oracle Corporation이 Java SE 8 릴리스에서 새로 도입한 방법입니다.

Java의 Iterator 예

아래는 Java의 Iterator 예입니다.

코드:

import java.io.*;
import java.util.*;
public class IteratorExample {
public static void main(String[] args)
{
ArrayList<String> val = new ArrayList<String>();
val.add("Iteration started");
val.add("Printing iteration1");
val.add("Printing iteration2");
val.add("Printing iteration3");
val.add("End of iteration");
// Iterates through the list
Iterator iter = val.iterator();
System.out.println("The values of iteration are as follows: ");
while (iter.hasNext())
System.out.println(iter.next() + " ");
System.out.println();
}
}
로그인 후 복사

출력:

Java의 반복자

반복자 메서드에서 예외가 발생함

요소 목록에서 반복자는 기존 요소에 대한 정보만 가져올 수 있습니다. 따라서 다음 반복에 존재하지 않는 요소에 액세스하려고 하면 충돌이 발생하거나 예외가 발생합니다. 여기서는 반복자 메서드를 구현하는 동안 발생하는 다양한 종류의 예외에 대해 알아 보겠습니다.

1. next() 메소드

요소 집합을 반복하고 이 방법으로 가져오는 동안

  • NoSuchElementException: 이는 next()가 현재 목록에 존재하지 않는 요소를 검색하려고 시도하는 경우 발생합니다. 따라서 next()를 호출하기 전에 항상 hasNext()를 사용해야 합니다.

2. 제거() 메소드

여기에서는 두 가지 종류의 예외가 발생할 수 있습니다.

  • IllegalStateException: next() 메서드 이전에 제거() 메서드가 호출되면 이 예외가 발생합니다. 이는 메소드가 next() 메소드에 의해 아직 지정되지 않은 요소를 제거하려고 시도하여 실패하기 때문입니다. 이 예외를 해결하려면 next()를 호출하여 첫 ​​번째 항목을 참조한 다음 제거()를 호출하여 목록에서 동일한 항목을 제거할 수 있습니다.
  • UnsupportedOperationException: 이 예외는 일반적으로 수정을 지원하지 않는 작업을 추가하거나 제거하여 목록 개체를 수정할 때 발생합니다. 예를 들어, Arrays.asList를 통해 배열을 목록으로 변환하려고 하면 이 예외가 발생합니다. 이는 래퍼가 ArrayList에서 List 객체를 생성할 때 List 객체의 크기가 고정되어 수정이 허용되지 않기 때문입니다. 이 문제를 해결하려면 추가/제거와 같은 작업을 수행하기 전에 Arrays.asList를 ArrayList 또는 LinkedList 개체로 변환하세요.

구문:

//ArrayList is created from the list having fixed size
list = new ArrayList<String>(list);
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
if( iter.next().equals("First iteration") ){
iter.remove();
}
}
로그인 후 복사

ListIterator의 메서드

이러한 메서드를 사용하면 반복자가 컬렉션 개체의 양방향으로 순회할 수 있습니다. 다음은 그 중 일부입니다:

  • add(): This method inserts the object value given and is returned when the next() method is called.
  • hasNext(): This method is the same as the one mentioned in iterator types, which returns Boolean true/false depending on the next element having a value or not.
  • hasPrevious(): This method is opposite to hasNext() and returns Boolean true if the list has a previous element and vice versa.
  • next(): This method retrieves the next element from the given list.
  • previous(): This method retrieves the previous element from the list.
  • remove(): This deletes the present element from the list. When this method is called either before the next() or previous() function, it throws “IllegalStateException”.

Example for ListIterator

Below is an example in ArrayList for ListIterator.

Code:

import java.util.*;
public class IteratorExample {
public static void main(String args[]) {
// Creating an array list
ArrayList array = new ArrayList();
// add elements to the array list
array.add("First element");
array.add("Second element");
array.add("Third element");
array.add("Fourth element");
array.add("Fifth element");
array.add("Sixth element");
// Displaying elements of an array
System.out.println("Printing input of the array: ");
Iterator iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.println(value + " ");
}
System.out.println();
// To update the elements of iteration
ListIterator listiter = array.listIterator();
while(listiter.hasNext()) {
Object value = listiter.next();
listiter.set(value + "+");
}
System.out.print("Updated array elements are as follows: ");
iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.print(value + " ");
}
System.out.println("\n");
// To display the contents in backward direction
System.out.println("Printing elements in backward direction: ");
while(listiter.hasPrevious()) {
Object value = listiter.previous();
System.out.print(value + " ");
}
System.out.println();
}
}
로그인 후 복사

Output:

Java의 반복자

Advantages of Iterators in Java

Below are the advantages of Iterators:

  1. It supports all classes under the Collection interface.
  2. The methods of an iterator are quite simple and easy to understand and implement.
  3. Elements of a Collection can be easily modified (add/remove) using Iterators.
  4. Accessing elements through Iterators will not lead to run-time exceptions.
  5. Data handling is efficient.
  6. It can iterate over various variables concurrently by holding each variable’s state of iteration separately.

Limitations of Iterators in Java

Below are the limitations of Iterators:

  1. Java iterator can iterate only in one direction, i.e. forward direction.
  2. It cannot be used to iterate between two different data structures concurrently.
  3. It cannot be used to backtrace an element.
  4. It does not allow modification of the structure of the element being iterated as it stores its position.
  5. It might be inefficient in certain cases were traversing through the elements directly is more efficient.

Conclusion

Iterators are the most commonly used method to retrieve elements from the collection interface. It is called Universal Java Cursor as it is applicable across all the Collection classes.

Recommended Article

This is a guide to Iterator in Java. Here we discuss methods and examples of Iterator in Java along with its Limitations and Advantages. You can also go through our other suggested articles to learn more –

  1. Overriding in Java
  2. Iterators in C#
  3. Java Collection Interview Questions
  4. Java Iterate Map

위 내용은 Java의 반복자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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