> Java > java지도 시간 > 본문

Java 컬렉션 프레임워크의 반복자 샘플 코드에 대한 자세한 설명

黄舟
풀어 주다: 2017-03-21 10:30:13
원래의
1225명이 탐색했습니다.

이 글에서는 주로 Java 컬렉션 프레임워크의 반복자에 대한 관련 정보를 간략하게 소개합니다. 여기에는 특정 참조 값이 있습니다. 관심 있는 친구는

Java의 배열 데이터를 참조할 수 있습니다. 인덱스, 객체는 어떻습니까? 또한 인덱스를 통해? 오늘은 Java 컬렉션에서 컬렉션 개체를 얻기 위한 iteration-Iterator 메서드를 분석하겠습니다.

본 글은 주로 Java 컬렉션 프레임워크인 Iterator에서 Iterator 부분을 분석하고 있습니다. 소스코드 분석은 분석 도구인 AndroidStudio인 JDK1.8을 기반으로 작성되었습니다.

1. 소개

JDK에서 제공하는 반복 인터페이스를 사용하여 Java 컬렉션을 반복하는 경우가 많습니다.

 Iterator iterator = list.iterator();
      while(iterator.hasNext()){
        String string = iterator.next();
        //do something
      }
로그인 후 복사

위는 반복자가 사용하는 기본 템플릿입니다. 실제로 반복은 다양한 컨테이너의 모든 개체를 순회하기 위한 표준화된 메서드 클래스인 순회로 간단하게 이해될 수 있습니다. 항상 Iterator를 제어하고 "앞으로", "뒤로" 및 "현재 요소 가져오기" 명령을 보내 전체 컬렉션을 간접적으로 탐색합니다. Java에서 Iterator는 반복에 대한 기본 규칙만 제공하는 인터페이스입니다.

  public interface Iterator<E> {
  //判断容器内是否还有可供访问的元素
  boolean hasNext();
  //返回迭代器刚越过的元素的引用,返回值是 E
  E next();
  //删除迭代器刚越过的元素
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }
}
로그인 후 복사

위는 특정 컬렉션을 통해 분석하는 반복자의 기본 선언입니다.

2. 컬렉션 분류

2.1 ArrayList의 반복자

ArrayList의 소스 코드를 분석하면 내부 클래스가 먼저 정의되어 있음을 알 수 있습니다. ArrayList Itr, 이 내부 클래스는 다음과 같이 Iterator 인터페이스를 구현합니다.

private class Itr implements Iterator<E> {
  //....
}
로그인 후 복사

는 내부 클래스에서 Iterator 인터페이스를 구현하고 ArrayList의 Iterator는 내부 클래스 Itr을 반환하므로 우리는 주로 Itr이 어떻게 구현되는지 살펴보세요.

  public Iterator<E> iterator() {
    return new Itr();
  }
로그인 후 복사

다음으로 내부 클래스 Itr의 구현을 분석해 보겠습니다.

  private class Itr implements Iterator<E> {

    protected int limit = ArrayList.this.size;

    int cursor;    // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
      return cursor < limit;
    }

    @SuppressWarnings("unchecked")
    public E next() {
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      int i = cursor;
      if (i >= limit)
        throw new NoSuchElementException();
      Object[] elementData = ArrayList.this.elementData;
      if (i >= elementData.length)
        throw new ConcurrentModificationException();
      cursor = i + 1;
      return (E) elementData[lastRet = i];
    }

    public void remove() {
      if (lastRet < 0)
        throw new IllegalStateException();
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();

      try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;
        expectedModCount = modCount;
        limit--;
      } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
      Objects.requireNonNull(consumer);
      final int size = ArrayList.this.size;
      int i = cursor;
      if (i >= size) {
        return;
      }
      final Object[] elementData = ArrayList.this.elementData;
      if (i >= elementData.length) {
        throw new ConcurrentModificationException();
      }
      while (i != size && modCount == expectedModCount) {
        consumer.accept((E) elementData[i++]);
      }
      // update once at end of iteration to reduce heap write traffic
      cursor = i;
      lastRet = i - 1;

      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    }
  }
로그인 후 복사

먼저 정의된 변수를 분석해 보겠습니다.

    protected int limit = ArrayList.this.size;

    int cursor;    // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;
로그인 후 복사

그 중limit는 현재 ArrayList의 크기, 커서는 다음 요소의 인덱스를 나타내고, lastRet 이전 요소의 인덱스입니다. 그렇지 않은 경우 예상ModCount는 거의 사용되지 않습니다. 그런 다음 반복 중에 후속 요소가 있는지 확인하는 방법을 분석하고 살펴보겠습니다.

  public boolean hasNext() {
      return cursor < limit;
  }
로그인 후 복사

다음 요소의 인덱스가 배열의 용량에 도달했는지 확인하는 것은 매우 간단합니다.

다음으로 현재 인덱스의 요소를 구하는 방법을 분석해 보겠습니다. next

    public E next() {
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      int i = cursor;
      if (i >= limit)
        throw new NoSuchElementException();
      Object[] elementData = ArrayList.this.elementData;
      if (i >= elementData.length)
        throw new ConcurrentModificationException();
      cursor = i + 1;
      return (E) elementData[lastRet = i];
    }
로그인 후 복사

다음 방법에서 modCount를 결정해야 하는 이유는 무엇인가요? 즉, 순회 프로세스 중에 컬렉션이 수정되었는지 여부를 확인하는 데 사용됩니다. modCount는 ArrayList 컬렉션의 수정 횟수를 기록하는 데 사용됩니다. 0으로 초기화됩니다. 추가, 제거 및 기타 메서드와 같이 컬렉션이 수정될 때마다(구조에 대한 수정, 내부 업데이트는 계산되지 않음) modCount + 1 , 따라서 modCount가 변경되지 않은 경우 컬렉션 내용이 수정되지 않았음을 의미합니다. 이 메커니즘은 주로 ArrayList 컬렉션의 빠른 실패 메커니즘을 구현하는 데 사용됩니다. Java 컬렉션 중 대부분의 컬렉션에는 빠른 실패 메커니즘이 있습니다. 따라서 순회 과정에서 오류가 발생하지 않도록 순회 과정에서 컬렉션에 구조적 수정이 이루어지지 않았는지 확인해야 합니다(물론 비정상적인 오류가 발생하는 경우에는 제거 메서드 제외). 캐치 후 처리가 수행되지 않습니다. 대신 프로그램에 오류가 있는지 여부. 위의 코드는 비교적 간단합니다. 인덱스의 배열 값만 반환합니다.

ArrayList의 iteration 방식은 주로 인덱스의 값을 판단하여 배열의 크기와 비교하여 순회할 데이터가 없는지 확인한 후 에서 값을 구한다. 배열은 주로 각 컬렉션을 캡처합니다. 기본 구현을 반복할 수 있습니다.

다음으로 HashMap의 Iterator 메서드를 분석하겠습니다. 기본 구현을 파악하는 한 다른 메서드도 비슷합니다.

2.2 HashMap의 Iterator

HashMap에도 Iterator 인터페이스를 구현하는 클래스가 있지만 이는 단지 추상 클래스일 뿐인 HashIterator를 살펴보겠습니다. 그것이 어떻게 구현되는지.

 private abstract class HashIterator<E> implements Iterator<E> {
    HashMapEntry<K,V> next;    // next entry to return
    int expectedModCount;  // For fast-fail
    int index;       // current slot
    HashMapEntry<K,V> current;   // current entry

    HashIterator() {
      expectedModCount = modCount;
      if (size > 0) { // advance to first entry
        HashMapEntry[] t = table;
        while (index < t.length && (next = t[index++]) == null)
          ;
      }
    }

    public final boolean hasNext() {
      return next != null;
    }

    final Entry<K,V> nextEntry() {
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      HashMapEntry<K,V> e = next;
      if (e == null)
        throw new NoSuchElementException();

      if ((next = e.next) == null) {
        HashMapEntry[] t = table;
        while (index < t.length && (next = t[index++]) == null)
          ;
      }
      current = e;
      return e;
    }

    public void remove() {
      if (current == null)
        throw new IllegalStateException();
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      Object k = current.key;
      current = null;
      HashMap.this.removeEntryForKey(k);
      expectedModCount = modCount;
    }
  }
로그인 후 복사

마찬가지로 다음 항목의 노드를 나타내기 위해 next 변수

    HashMapEntry<K,V> next;    // next entry to return
    int expectedModCount;  // For fast-fail
    int index;       // current slot
    HashMapEntry<K,V> current;   // current entry
로그인 후 복사

도 정의합니다. 빠른 수집 실패 메커니즘. Index는 현재 인덱스를 나타내고, 현재의 인덱스가 나타내는 노드 항목은 다음 요소에 대한 값이 있는지 확인하는 방법을 살펴보겠습니다.

next가 null인지 확인하는 것은 매우 간단합니다. null이면 데이터가 없다는 의미입니다.

그럼 요소 획득 방법을 분석해 보세요

    final Entry<K,V> nextEntry() {
      if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
      HashMapEntry<K,V> e = next;
      if (e == null)
        throw new NoSuchElementException();
      // 一个Entry就是一个单向链表
      // 若该Entry的下一个节点不为空,就将next指向下一个节点;
      // 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。
      if ((next = e.next) == null) {
        HashMapEntry[] t = table;
        while (index < t.length && (next = t[index++]) == null)
          ;
      }
      current = e;
      return e;
    }
로그인 후 복사

위 내용은 Java 컬렉션 프레임워크의 반복자 샘플 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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