System.Collections.ArrayList 클래스는 특수 배열입니다. 요소를 추가하고 제거하면 배열의 길이를 동적으로 변경할 수 있습니다.
하나. 이점
1. 자동 크기 변경 기능을 지원합니다
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 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 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
네. 삭제
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에서 다양한 요소를 제거합니다. 인덱스는 인덱스를 나타내고 카운트는 인덱스에서 시작하는 숫자를 나타냅니다.
alist.add ( "a"); alist.add ( "b"); alist.add ( "c"); alist.add ( "d"); alist.add ( "e"); alist.removerange (1,3);
결과는입니다
다음과 같이 코드를 복사하십시오. ae
4. PublicVirtualVoidClear ();
ArrayList에서 모든 요소를 제거하십시오.
다섯. 종류
1.publicVirtualVoidSort ();
Arraylist 또는 일부에 요소를 정렬하십시오.
ArrayListalist = newArrayList (); alist.add ( "e"); alist.add ( "a"); alist.add ( "b"); alist.add ( "c"); alist.add ( "d"); dropdownlist1.datasource = alist; // dropdownlistdropdownlist1; dattaBind (dropdownListDropDownList1);
결과는입니다
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 (); // reverse dropdownList1.datasource = alist; // dropdownListDropdownList1; DropDownList1.databind ();
결과는입니다
EDCBA
육. 찾다
1. PublicVirtualIntIndexof (Object);
2. PublicVirtualIntIndexof (Object, int);
3. PublicVirtualIntIndexof (Object, int, int);
배열 목록 또는 그 일부의 첫 번째 일치의 0 기반 인덱스를 반환합니다. 반품 -1은 발견되지 않았습니다.
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"); // 값은 0 대신 2입니다
7. PublicVirtualBoolContains (ObjectItem);
요소가 Arraylist에 있는지 여부를 결정합니다. 포함 된 경우 true를 반환하고 그렇지 않으면 False를 반환하십시오
일곱. 다른
1. PublicVirtualIntCapacity {get; set;}
배열 목록에 포함 할 수있는 요소 수를 가져 오거나 설정합니다.
2. publicvirtualIntCount {get;}
Arraylist에 실제로 포함 된 요소 수를 가져옵니다.
용량은 Arraylist가 저장할 수있는 요소 수입니다. 카운트는 Arraylist에 실제로 포함 된 요소 수입니다. 용량은 항상 카운트보다 크거나 동일합니다. 요소를 추가 할 때 카운트가 용량을 초과하면 내부 배열을 자동으로 재 할당하여 목록의 용량이 두 배가됩니다.
용량 값이 명시 적으로 설정되면 지정된 용량을 수용하기 위해 내부 배열도 재 할당해야합니다. 용량이 0으로 명시 적으로 설정되면 공통 언어 런타임은 기본 용량으로 설정합니다. 기본 용량은 16입니다.
Clear를 호출 한 후 Count는 0 이고이 시점에서 용량 삭감은 기본 용량 16입니다.
3. PublicVirtualVoidTrimTosize ();
Arraylist의 실제 요소 수로 용량을 설정하십시오.
목록에 새 요소를 추가하지 않으면이 방법을 사용하여 목록의 메모리 시스템 오버 헤드를 최소화 할 수 있습니다.
목록의 모든 요소를 완전히 지우려면 TrimTosize를 호출하기 전에 명확한 방법을 호출하십시오. 빈 배열 목록을 차단하면 배열리스트의 용량이 0이 아닌 기본 용량으로 설정됩니다.
ArrayList alist = new ArrayList (); alist.add ( "a"); alist.add ( "b"); alist.add ( "c"); alist.add ( "d"); alist.add ( "e"); // caper = 16, alist.trimtosize (); // 용량 = 5;
8. 소스 코드 분석
목록 인터페이스의 구현 클래스는 내부적으로 배열을 사용하여 요소 값을 저장하는데, 이는 변수 크기의 배열과 동일합니다.
1. 서명
Public Class ArrayList <E>는 AbstractList <e>를 확장하여 목록 <e>, RandomAccess, 클로닝 가능, 직렬화 가능합니다
ArrayList가 AbstractList Abstract 클래스를 상속하는 것을 볼 수 있으며, 이는 목록 인터페이스의 대부분의 메소드를 구현합니다. 불변의 목록을 구현하려면이 클래스를 물려 받고 get (int) 및 크기 메소드를 구현하십시오. 변이 가능한 목록을 구현하려면 세트 (int, e)를 무시해야합니다. 또한 목록의 크기가 가변적 인 경우 add (int, e) 및 remove () 메소드도 재정의해야합니다.
2. 생성자
ArrayList는 세 가지 생성자를 제공합니다.
ArrayList () ArrayList (collection <? extends e> c) arraylist (int initialcapacity)
각 컬렉션 클래스가 두 개의 "표준"생성자를 제공해야한다는 컬렉션 인터페이스 컨벤션, 하나는 매개 변수가없는 생성자이며, 다른 하나는 단일 매개 변수가있는 생성자입니다 (위의 두 번째). ArrayList는 또한 arrayli의 초기 크기를 설정하기 위해 int 값을 수용하는 세 번째 생성자를 제공합니다 (기본 크기는 10).
3. 관련 방법
trimtosizepublic void trimtosize () {modcount ++; int OldCapacity = ElementData.length; if (size <OldCapacity) {ElementData = arrays.copyof (elementData, size); }}Arraylist의 용량을 현재 실제 크기로 줄이고 저장 용량을 줄이는 데 사용됩니다. 변수 modcount는 AbstractList에서 상속되어 목록이 구조적으로 수정 된 횟수를 기록합니다. Arraylist의 요소는 실제로 ElementData에 저장되며 다음과 같이 선언됩니다. 변수 크기는 Arraylist의 요소 수입니다. 크기 <oldcapacity는 arrays.copyof method를 호출하여 감소를 달성하십시오.
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; } 반환 -1; }이 두 가지 방법은 지정된 요소의 첨자를 반환하고 매개 변수가 NULL인지 구별하려고합니다. LastIndexof는 indexof와 유사하지만 뒤에서 앞뒤로 검색합니다.
5. ensurecapacity
공공 void ensurecapacity (int mincapacity) {if (mincapacity> 0) ensurecapacity internal (mincapacity); } private void ensureCapacityInternal (int mincapacity) {modcount ++; // 오버 플로우에 민감한 코드 if (minCapacity -ElementData.length> 0) grow (mincapacity); } private void grow (int mincapacity) {// 오버 플로우에 민감한 코드 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는 일반적으로 크기에 가깝기 때문에 이것은 다음과 같습니다. elementData = arrays.copyof (elementData, newCapacity); }이 방법은 Arraylist의 크기를 보장합니다
6. add and addall
public void add (int index, e element) {rangecheckforadd (index); ensurecapacity internal (size + 1); // MODCOUNT를 증가시킵니다 !! System.ArrayCopy (ElementData, Index, ElementData, Index + 1, Size -Index); ElementData [index] = 요소; 크기 ++; } 지정된 위치에 요소를 추가하려면 (int index, e 요소)를 추가하십시오. 먼저, rangecheckforadd에 전화하여 인덱스가 유효한지 확인하십시오. 인덱스> 크기 || 인 경우 인덱스 <0, 예외가 발생합니다. 그런 다음 용량이 1 씩 증가하고 시스템을 호출하여 요소를 한 위치에서 시작하여 요소를 한 위치에서 뒤로 이동시킵니다. 마지막으로 인덱스에서 값을 추가 요소로 설정하십시오. 요소를 끝에 직접 추가하는 과부하 ADD (E E) 메소드도 있습니다.
addall (collection <? extends e> c) 및 addall (int index, collection <? extends e> c) 컬렉션의 모든 요소를 각각 끝과 지정된 위치에 추가합니다.
7. 제거 및 removeall
public boolean remove (object o) {if (o == null) {for (int index = 0; index <size; index ++) if (elementData [index] == null) {fastremove (index); 진실을 반환하십시오. }} else {for (int index = 0; index <size; index ++) if (o.equals (elementData [index]) {fastremove (index); 진실을 반환하십시오. }} 거짓을 반환합니다. }제거 (개체 O) 메소드는 지정된 요소를 삭제합니다. 먼저 요소 위치를 찾은 다음 Fastremove (index)를 호출하여 삭제하십시오. 코드는 다음과 같습니다.
개인 void fastremove (int index) {modcount ++; int nummoved = size -index -1; if (nummoved> 0) // index+1 뒤에 모든 요소를 이동합니다. 1 한 위치 전방 System.ArrayCopy (ElementData, index+1, elementData, index, nummoved); ElementData [-size] = null; // GC가 작동하도록하자} 오버로드 된 제거 (int index) 메소드는 지정된 위치에서 요소를 삭제하는 데 사용됩니다. 리버지랑 (int fromIndex, int toIndex)은 지정된 위치 사이의 모든 요소를 삭제하는 데 사용됩니다.
removeall (collection <?> c) 및 retainall (collection <?> c) 코드는 다음과 같습니다.
public boolean removeall (collection <?> c) {objects.requirenonnull (c); BatchRemove 리턴 (C, False); } public boolean retainall (collection <?> c) {objects.requirenonnull (c); 반환 BatchRemove (C, True); }이들은 모두 BatchRemove 메소드를 호출하여 구현되며 코드는 다음과 같습니다.
개인 부울 BatchRemove (Collection <?> C, 부울 보완) {Final Object [] elementData = this.ElementData; int r = 0, w = 0; 부울 수정 = 거짓; try {for (; r <size; r ++) if (c.contains (elementData [r]) == 보완) ElementData [w ++] = ElementData [r]; } 마침내 {// actractCollection과의 행동 호환성을 보존하십시오. if (r! = size) {System.ArrayCopy (ElementData, R, ElementData, W, Size -R); W += 크기 -R; } if (w! = size) {// gc가 작동하도록 지우십시오 (int i = w; i <size; i ++) ementdata [i] = null; modcount += size -w; 크기 = w; 수정 = true; }} 리턴 수정; }이 방법에는 두 가지 매개 변수가 있습니다. 첫 번째는 작전 컬렉션이고 두 번째는 부울 값입니다. true 또는 false로 설정하면 Removeall 또는 retainall 의지 여부를 선택합니다. Try의 진술은 나머지 진술을 0과 w 사이에 놓고 마지막으로 두 번째는 W 이후 공간을 처리하고 C.contains ()가 예외를 던지면 첫 번째는 실행됩니다.