JAVA中的ArrayList用法
List介面下一共實現了三個類:ArrayList,Vector,LinkedList。
LinkedList主要保持資料的插入順序的時候使用,採用連結串列結構。
ArrayList,Vector主要區別為以下幾點:
(1):Vector是執行緒安全的,原始碼中有很多的synchronized可以看出,而ArrayList不是。導致Vector效率無法和ArrayList相比;
(2):ArrayList和Vector都採用線性連續儲存空間,當儲存空間不足的時候,ArrayList預設增加為原來的50%,Vector預設增加為原來的一倍;
(3):Vector可以設定capacityIncrement,而ArrayList不可以,從字面理解就是capacity容量,Increment增加,容量增長的引數。
List<?> ?表示不確定型別,其實表示的是Object型別。
List<E> E是自己定義的,相當於引數臨時名而已,例如public <T> void add(T t){}
List<? extends Person> 泛型向上限定,也就是說傳入的?必須是Person的子類。
List<? super Person> 泛型向下限定,也就是傳入的?必須是Person的父類。
高階篇:泛型只作用域javac編譯,其實就是編譯時作為一個檢測,比如List<String>編譯完畢後,我們使用反射得到getClass(),呼叫add方法,插入int,這是測試成功的。由此而建,泛型只是一個編譯型別檢測功能。
swap(List<?>, int, int)
宣告
以下是java.util.Collections.swap()方法的宣告。
publicstaticvoid swap(List<?> list,int i,int j)
引數
list-- 在該列表中的調劑元素。
i-- 要交換的一個元素的索引。
j-- 要交換的其它元素的索引。
返回值
NA
異常
IndexOutOfBoundsException-- 如果不是i或j超出這個範圍(i < 0 || i >= list.size() || j < 0 || j >= list.size()),則會引發。
例子
下面的例子顯示java.util.Collections.swap()方法的使用
package com.yiibai;import java.util.*;publicclassCollectionsDemo{publicstaticvoid main(String[] args){// create vector object Vector<String< vector =newVector<String<();// populate the vector vector.add("1"); vector.add("2"); vector.add("3"); vector.add("4"); vector.add("5");System.out.println("Before swap: "+vector);// swap the elementsCollections.swap(vector,0,4);System.out.println("After swap: "+vector);}}
現在編譯和執行上面的程式碼示例,將產生以下結果。
Before swap:[1,2,3,4,5]After swap:[5,2,3,4,1]
import java.util.Collections;
private ArrayList<ProgramInfo> progInfoList = new ArrayList<ProgramInfo>();
Collections.swap(progInfoList,0,1); //交換元素的位置
一:ArrayList結構圖
簡單說明:
1、上圖中虛線且無依賴字樣、說明是直接實現的介面
2、虛線但是有依賴字樣、說明此類依賴與介面、但不是直接實現介面
3、實線是繼承關係、類繼承類、介面繼承介面
二:ArrayList類簡介:
1、ArrayList是內部是以動態陣列的形式來儲存資料的、知道陣列的可能會疑惑:陣列不是定長的嗎?
這裡的動態陣列不是意味著去改變原有內部生成的陣列的長度、而是保留原有陣列的引用、將其指向新生成的陣列物件、
這樣會造成陣列的長度可變的假象。
2、ArrayList具有陣列所具有的特性、通過索引支援隨機訪問、所以通過隨機訪問ArrayList中的元素效率非常高、
但是執行插入、刪除時效率比較地下、具體原因後面有分析。
3、ArrayList實現了AbstractList抽象類、List介面、所以其更具有了AbstractList和List的功能、
前面我們知道AbstractList內部已經實現了獲取Iterator和ListIterator的方法、所以ArrayList只需關心對陣列操作的方法的實現。
4、ArrayList實現了RandomAccess介面、此介面只有宣告、沒有方法體、表示ArrayList支援隨機訪問。
5、ArrayList實現了Cloneable介面、此介面只有宣告、沒有方法體、表示ArrayList支援克隆。
6、ArrayList實現了Serializable介面、此介面只有宣告、沒有方法體、表示ArrayList支援序列化、
即可以將ArrayList以流的形式通過ObjectInputStream/ObjectOutputStream來寫/讀。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
三:ArrayList API
// Collection中定義的API
boolean add(E object)
boolean addAll(Collection<? extends E> collection)
void clear()
boolean contains(Object object)
boolean containsAll(Collection<?> collection)
boolean equals(Object object)
int hashCode()
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object object)
boolean removeAll(Collection<?> collection)
boolean retainAll(Collection<?> collection)
int size()
<T> T[] toArray(T[] array)
Object[] toArray()
// AbstractList中定義的API
void add(int location, E object)
boolean addAll(int location, Collection<? extends E> collection)
E get(int location)
int indexOf(Object object)
int lastIndexOf(Object object)
ListIterator<E> listIterator(int location)
ListIterator<E> listIterator()
E remove(int location)
E set(int location, E object)
List<E> subList(int start, int end)
// ArrayList新增的API
Object clone()
void ensureCapacity(int minimumCapacity)
void trimToSize()
void removeRange(int fromIndex, int toIndex)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
總結:相對與AbstractCollection而言、多實現了List中新增的通過索引操作元素的方法。
四:ArrayList原始碼分析
package com.chy.collection.core;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.RandomAccess;
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8683452581122892189L;
/** 儲存ArrayList中元素的陣列*/
private transient Object[] elementData;
/** 儲存ArrayList中元素的陣列的容量、即陣列的size*/
private int size;
/** 使用指定的大小建立ArrayList*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = new Object[initialCapacity];
}
/** 使用預設的大小建立ArrayList*/
public ArrayList() {
this(10);
}
/**
* 使用指定的Collection構造ArrayList、構造之後的ArrayList中包含Collection中的元素、
* 這些元素的排序方式是按照ArrayList的Iterator返回他們時候的順序排序的
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
/**
* 將此 ArrayList 例項的容量調整為列表的當前大小
*/
public void trimToSize() {
//此集合總共被修改的次數
modCount++;
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
/**
* 確保此ArrayList的最小容量能容納下引數minCapacity指定的容量、
* 1、minCapacity大於原來容量、則將原來的容量增加(oldCapacity * 3)/2 + 1;
* 2、若minCapacity仍然大於增加後的容量、則使用minCapacity作為ArrayList容量
* 3、若minCapacity不大於增加後的容量、則使用增加後的容量。
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
/** 返回此列表中的元素的個數*/
public int size() {
return size;
}
/** 如果此列表中沒有元素,則返回 true*/
public boolean isEmpty() {
return size == 0;
}
/** 如果此列表中包含指定的元素,則返回 true。*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/** 返回指定物件在ArrayList中存放的第一個位置索引、注意空值的處理和Object.equals(? extends Object o)的返回值、不存在的話返回-1*/
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;
}
/** 返回指定物件在ArrayList中存放最後一個位置的索引、注意空值的處理和Object.equals(? extends Object o)的返回值、不存在的話返回-1*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/** 返回一個當前集合的淺clone物件*/
public Object clone() {
try {
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/** 將當前ArrayList轉換成Object陣列、注意操作使用此方法轉換後的陣列有可能拋異常*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 將當前ArrayList轉換成與傳入的T型別相同的陣列、當傳入的a的length小於ArrayList的size的時候、方法內部會生成一個新的T[]返回
* 如果傳入的T[]的length大於ArrayList的size、則T[]從下標size開始到最後的元素都自動用null填充。
*/
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
/** 獲取ArrayList中索引為index位置的元素*/
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
/** 將ArrayList的索引為index處的元素使用指定的E元素替換、返回被替換的原來的元素值*/
public E set(int index, E element) {
RangeCheck(index);
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
/** 將指定元素E新增到ArrayList的結尾處*/
public boolean add(E e) {
//確保ArrayList的容量能夠新增新的的元素
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/** 將指定元素新增到指定的索引處 、
* 注意:
* 1、如果指定的index大於Object[] 的size或者小於0、則拋IndexOutOfBoundException
* 2、檢測Object[]是否需要擴容
* 3、 將從index開始到最後的元素後移一個位置、
* 4、將新新增的元素新增到index去。
*/
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
/** 與add類似、
* 1、將指定index處的元素刪除、
* 2、將index之後的所有元素前一一個位置、最後一個
* 3、將最後一個元素設定為null、--size
*
* 返回被刪除的元素。
*/
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
/** 刪除Object[]中指定的元素Object 類似與contains方法與remove的結合體、只不過這裡使用的是fastRemove方法去移除指定元素、移除成功則返回true*/
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;
}
/* 刪除指定索引處的元素、不返回被刪除的元素*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
/** 清空ArrayList*/
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/** 將指定集合中的所有元素追加到ArrayList中(從最後開始追加)*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/** 將指定集合中的所有元素插入到idnex開始的後面位置處、原有的元素往後排*/
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
/** 移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之間的所有元素。
* 1、將Object[] 從toIdnex開始之後的元素(包括toIndex處的元素)移到Object[]下標從fromIndex開始之後的位置
* 2、若有Object[]尾部要有剩餘的位置則用null填充
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newSize = size - (toIndex-fromIndex);
while (size != newSize)
elementData[--size] = null;
}
/** 檢測下標是否越界*/
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
/** 將此ArrayList寫入到ObjectOutputStream流中、先寫ArrayList存放元素的Object[]長度、再將Object[]中的每個元素寫入到ObjectOutputStream流中*/
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/** 從ObjectInputStream中讀取ArrayList、先讀取ArrayList中Object[]的長度、再讀取每個元素放入Object []中對應的位置*/
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301