Java에서 ArrayList 클래스의 사용법과 원본 코드 완전 해석

12384 단어 JavaArrayList
System.Collections.ArrayList 클래스는 특수한 배열입니다.요소를 추가하고 삭제하면 그룹의 길이를 동적으로 변경할 수 있습니다.
장점
1. 자동 크기 변경 기능 지원
2. 유연한 요소 삽입 가능
3. 원소를 유연하게 삭제할 수 있다
2. 한계성
일반적인 수조에 비하면 속도가 좀 떨어진다
3. 요소 추가
1.publicvirtualintAdd(objectvalue);
ArrayList 끝에 객체 추가

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
내용

abcde
2.publicvirtualvoidInsert(intindex,objectvalue);
ArrayList의 지정된 색인에 요소 삽입

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Insert(0,"aa");
결과

aaabcde
3.publicvirtualvoidInsertRange(intindex,ICollectionc);
ArrayList의 지정된 색인에 컬렉션의 요소 삽입

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
ArrayList list2 = newArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2,list2);
결과

abtttttcde
4. 삭제
1. publicvirtualvoidRemove(objectobj);
ArrayList에서 특정 객체의 첫 번째 일치 항목을 제거합니다.

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Remove("a");
결과

bcde
2. publicvirtualvoidRemoveAt(intindex);
ArrayList의 지정된 색인에서 요소 제거

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveAt(0);
결과

bcde
3.publicvirtualvoidRemoveRange(intindex,intcount);
ArrayList에서 특정 범위의 요소를 제거합니다.Index는 색인을 나타내고, count는 색인에서 시작하는 수를 나타냅니다.

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveRange(1,3);
결과
ae
4.publicvirtualvoidClear();
ArrayList에서 모든 요소를 제거합니다.
5. 정렬
1. publicvirtualvoidSort();
ArrayList 또는 해당 요소의 일부를 정렬합니다.

ArrayListaList=newArrayList();
aList.Add("e");
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
결과

eabcd

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Sort();// 
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
결과

abcde
2.publicvirtualvoidReverse();
ArrayList 또는 요소의 일부 순서를 반전합니다.

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Reverse();// 
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
결과

edcba
찾다
1.publicvirtualintIndexOf(object);
2. publicvirtualintIndexOf(object,int);
3. publicvirtualintIndexOf(object,int,int);
ArrayList나 그 일부분의 값의 첫 번째 일치하는 항목의 0부터 시작하는 인덱스를 되돌려줍니다.되돌릴 수 없습니다.

  ArrayList aList = new ArrayList();
  aList.Add("a");
  aList.Add("b");
  aList.Add("c");
  aList.Add("d");
  aList.Add("e");
  intnIndex=aList.IndexOf(“a”);//1
  nIndex=aList.IndexOf(“p”);// ,-1
4.publicvirtualintLastIndexOf(object);
5.publicvirtualintLastIndexOf(object,int);
6.publicvirtualintLastIndexOf(object,int,int);
ArrayList나 그 일부분의 값의 마지막 일치하는 항목의 0부터 시작하는 인덱스를 되돌려줍니다.

  ArrayList aList = new ArrayList();
  aList.Add("a");
  aList.Add("b");
  aList.Add("a");// 0
  aList.Add("d");
  aList.Add("e");
  intnIndex=aList.LastIndexOf("a");// 2 0
7. publicvirtualboolContains(objectitem);
요소가 ArrayList에 있는지 확인합니다.반환true 포함, 그렇지 않으면false 반환
기타
1.publicvirtualintCapacity{get;set;}
ArrayList에 포함할 수 있는 요소 수를 가져오거나 설정합니다.
2.publicvirtualintCount{get;}
ArrayList에 실제로 포함된 요소 수를 가져옵니다.
Capacity는 ArrayList가 저장할 수 있는 요소 수입니다.Count는 ArrayList에 실제로 포함된 요소 수입니다.Capacity는 항상 Count보다 크거나 같습니다.요소를 추가할 때 Count가 Capacity를 초과하면 목록의 용량은 내부 그룹을 자동으로 재분배하여 두 배로 증가합니다.
Capacity 값이 명시적으로 설정된 경우 내부 배열도 지정된 용량을 수용하도록 재할당해야 합니다.Capacity가 0으로 명시적으로 설정된 경우 공용 언어 라이브러리는 이를 기본 용량으로 설정합니다.기본 용량은 16입니다.
Clear를 호출한 후 Count는 0이고 Capacity는 0이 아닌 기본 용량 16입니다.
3.publicvirtualvoidTrimToSize();
용량을 ArrayList의 실제 요소로 설정합니다.
목록에 새 요소를 추가하지 않으면 목록의 메모리 시스템 비용을 최소화할 수 있습니다.
목록에서 모든 요소를 완전히 지우려면 TrimToSize를 호출하기 전에 Clear 메서드를 호출합니다.빈 ArrayList를 차단하면 ArrayList의 용량이 0이 아닌 기본 용량으로 설정됩니다.

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");//Count=5,Capacity=16,
aList.TrimToSize();//Count=Capacity=5;
여덟원본 분석
List 인터페이스의 실현 클래스로 내부는 하나의 수조로 요소 값을 저장하는데 가변 크기의 수조에 해당한다.
1. 서명

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
ArrayList가 AbstractList 추상적인 클래스를 계승하여 List 인터페이스의 대다수 방법을 실현한 것을 볼 수 있다.변하지 않는 List를 실현하려면 이 클래스를 계승하고 get (int) 와size 방법을 실현하십시오.가변 목록을 만들려면 set(int, E)을 덮어써야 합니다.또한 List의 크기가 가변적이면add(int, E)와remove() 방법을 덮어씁니다.
2. 구조기
ArrayList는 다음과 같은 세 가지 구조물을 제공합니다.

ArrayList()
ArrayList(Collection<? extends E> c)
ArrayList(int initialCapacity)
Collection 인터페이스는 모든 집합 클래스는 두 개의 표준 구조기를 제공해야 한다고 약정했다. 하나는 매개 변수가 없는 구조기(위 첫 번째)이고, 다른 하나는 하나의 매개 변수 (유형은 Collettion) 를 가진 구조기 (위 두 번째) 이다.ArrayList는 ArrayLi의 초기 크기(기본 크기는 10)를 설정하는 데 사용할 int 값을 수락하는 세 번째 구조기도 제공합니다.
3. 관련 방법

trimToSize
public void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
      elementData = Arrays.copyOf(elementData, size);
    }
  }
ArrayList의 용량을 현재 실제 크기로 줄이고 저장 용량을 줄이는 데 사용됩니다.그 중 변수modCount는 AbstracList에서 계승되어 List에 구조화된 수정 (structurally modified) 이 발생한 횟수를 기록합니다.elementData에는 ArrayList의 요소가 실제로 저장되어 있으며, ArrayList에는 다음과 같이 명시되어 있습니다. private transient Object[] elementData;변수 size는 ArrayList의 요소 수량으로 size < oldCapacity 에서 Arrays 를 호출합니다.copyOf 방법은 축소를 실현한다.
4. indexOf 및 lasIndexOf

public int indexOf(Object o) {
    if (o == null) {
      for (int i = 0; i < size; i++)
        if (elementData[i]==null)
          return i;
    } else {
      for (int i = 0; i < size; i++)
        if (o.equals(elementData[i]))
          return i;
    }
    return -1;
  }
이 두 가지 방법은null인지 아닌지를 구분하기 위해 지정한 요소의 아래 표를 되돌려줍니다.last Index Of는 index Of와 유사합니다. 단지 뒤에서 앞으로 검색할 뿐입니다.
5.ensureCapacity

public void ensureCapacity(int minCapacity) {
    if (minCapacity > 0)
      ensureCapacityInternal(minCapacity);
  }
private void ensureCapacityInternal(int minCapacity) {
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
      grow(minCapacity);
  }
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
      newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
      newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
  }
이 방법은 Array List의 크기를 확보할 수 있습니다.
6.add 및 addAll

public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1); // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
    elementData[index] = element;
    size++;
  }

add(int index, E element)는 지정된 위치에 요소를 추가합니다. 우선 rangeCheckForAdd를 호출하여 index가 유효한지 확인합니다. index > size | | index < 0에서 이상이 발생합니다.그리고 용량을 1을 추가하고 시스템을 호출합니다.arraycopy는 index에서 시작된 요소를 뒤로 이동합니다.마지막으로 index의 값을 추가 요소로 설정합니다.다시 불러오는 add(E e) 방법은 원소를 끝에 직접 추가하는 것입니다.
addAll(Collectionc)과addAll(int index, Collectionc)은 각각 Collection의 모든 요소를 끝과 지정된 위치에 추가합니다.
7.remove 및 removeAll

public boolean remove(Object o) {
    if (o == null) {
      for (int index = 0; index < size; index++)
        if (elementData[index] == null) {
          fastRemove(index);
          return true;
        }
    } else {
      for (int index = 0; index < size; index++)
        if (o.equals(elementData[index])) {
          fastRemove(index);
          return true;
        }
    }
    return false;
  }
remove(Object o) 메서드는 지정된 요소를 삭제합니다.먼저 요소 위치를 찾은 다음 fastRemove(index)를 호출하여 삭제합니다. 코드는 다음과 같습니다.

private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
      // index+1 
      System.arraycopy(elementData, index+1, elementData, index,
               numMoved);
    elementData[--size] = null; // Let gc do its work
  }
다시 불러오는 remove (int index) 방법은 지정한 위치의 요소를 삭제하는 데 사용됩니다.removeRange(int fromIndex, int toIndex)는 지정된 위치 사이의 모든 요소를 삭제하는 데 사용됩니다.
removeAll(Collection c) 및 retainAll(Collection c) 코드는 다음과 같습니다.

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
  }
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
  }
그것들은 모두 batchRemove 호출 방법을 통해 이루어진 것이다. 그 코드는 다음과 같다.

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
      for (; r < size; r++)
        if (c.contains(elementData[r]) == complement)
          elementData[w++] = elementData[r];
    } finally {
      // Preserve behavioral compatibility with AbstractCollection,
      // even if c.contains() throws.
      if (r != size) {
        System.arraycopy(elementData, r,
                 elementData, w,
                 size - r);
        w += size - r;
      }
      if (w != size) {
        // clear to let GC do its work
        for (int i = w; i < size; i++)
          elementData[i] = null;
        modCount += size - w;
        size = w;
        modified = true;
      }
    }
    return modified;
  }
이 방법은 두 개의 매개 변수가 있는데 첫 번째는 조작된 Collection이고, 두 번째는 부울 값입니다. true 또는false로 설정하여removeAll인지retainAll인지 선택하십시오.try 안의 문장은 남겨진 것을 0에서 w 사이에 놓고finally에서 두 번째if로 w를 처리한 다음 공간입니다. 첫 번째는 c.contains () 가 이상을 던졌을 때 실행합니다.

좋은 웹페이지 즐겨찾기