> Java > Java베이스 > 본문

Java에서 ArrayList 컬렉션을 초기화하는 방법

王林
풀어 주다: 2019-11-26 15:13:01
앞으로
2613명이 탐색했습니다.

Java에서 ArrayList 컬렉션을 초기화하는 방법

Overview

ArrayList는 동적 배열을 기반으로 하는 스레드로부터 안전하지 않은 컬렉션입니다. ArrayList의 요소는 비어 있고 반복 가능하며 동시에 정렬될 수 있습니다(읽기 및 저장 순서는 일관됩니다).

ArrayList는 AbstractList를 상속하고 ListRandomAccess(可以快速访问)、Cloneable(可以被克隆)、java.io.Serializable(직렬화 지원)을 구현합니다.

더 많은 무료 관련 동영상 권장 사항: java video

ArrayList를 초기화하는 방법에는 세 가지가 있습니다.

1. 매개변수 없는 구성, 기본 길이는 다음과 같습니다. 10은 가장 일반적으로 사용되는 초기화 방법입니다.

/**
  * Constructs an empty list with an initial capacity of ten.
  */
  public ArrayList() {
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  }
로그인 후 복사

이제 소스 코드에서 코드 한 줄만 볼 수 있습니다. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA, 정의된 DEFAULTCAPACITY_EMPTY_ELEMENTDATA는 다음에서 찾을 수 있습니다. 소스 코드:

/**
  * Shared empty array instance used for default sized empty instances. We
  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  * first element is added.
  */
 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
로그인 후 복사

소스 코드에는 빈 배열이 기본 크기로 정의되어 있으며, 첫 번째 요소가 추가될 때 배열을 얼마나 확장할지가 결정된다는 것을 주석에서 알 수 있습니다. 요소 추가의 다음 섹션에서.

2. 초기화 길이 지정:

/**
  * Constructs an empty list with the specified initial capacity.
  * @param  initialCapacity  the initial capacity of the list
  * @throws IllegalArgumentException if the specified initial capacity
  *         is negative
  */
  public ArrayList(int initialCapacity) {
     if (initialCapacity > 0) {
         this.elementData = new Object[initialCapacity];
     } else if (initialCapacity == 0) {
         this.elementData = EMPTY_ELEMENTDATA;
     } else {
         throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
     }
  }
로그인 후 복사

3. Collection 객체를 사용하여

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
로그인 후 복사

권장 관련 기사 및 튜토리얼: Java 개발 시작하기

위 내용은 Java에서 ArrayList 컬렉션을 초기화하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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