java中ArrayList用法详解,基本用法(含增删改查)
生活随笔
收集整理的這篇文章主要介紹了
java中ArrayList用法详解,基本用法(含增删改查)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、什么是ArrayList?
ArrayList就是 動態數組,它提供了
①動態的增加和減少元素?
②實現了ICollection和IList接口?
有時候,當我們調用ArrayList中的 toArray(),可能遇到過拋出java.lang.ClassCastException異常的情況,這是由于toArray() 返回的是 Object[] 數組,將 Object[] 轉換為其它類型(如,將Object[]轉換為的Integer[])則會拋出java.lang.ClassCastException異常,因為Java不支持向下轉型。?
ArrayList就是 動態數組,它提供了
①動態的增加和減少元素?
②實現了ICollection和IList接口?
③靈活的設置數組的大小
ArrayList是一個其容量能夠動態增長的動態數組。它繼承了AbstractList,實現了List、RandomAccess, Cloneable, java.io.Serializable。?
基本的ArrayList,長于隨機訪問元素,但是在List中間插入和移除元素時較慢。同時,ArrayList的操作不是線程安全的!
一般在單線程中才使用ArrayList,而在多線程中一般使用Vector或者CopyOnWriteArrayList。
2、如何使用ArrayList?
最簡單的例子:
?ArrayList<Integer> a=new ArrayList<Integer>(); for(int i=0; i<n; i++){ a.add(sc.nextInt()); //為數組增加int型數} a.remove(0);//刪除第一個元素;m=2; a.add(m); //在數組末尾添加a.add(4,2);// 在指定位置添加元素,在第5個位置添加2 a.remove(2); // 刪除指定位置上的元素 a.remove((Object)3); // 刪除指定元素a.clear(); // 清空ArrayList System.out.println("ArrayList contains 5 is: " + a.contains(5));// 判斷arrayList是否包含5 System.out.println("ArrayList is empty: " + arrayList.isEmpty()); // 判斷ArrayList是否為空3、ArrayList有三種遍歷方式
迭代器遍歷 Iterator<Integer> it = arrayList.iterator(); while(it.hasNext()){System.out.print(it.next() + " "); } 索引值遍歷 for(int i = 0; i < arrayList.size(); i++){System.out.print(arrayList.get(i) + " "); }for循環遍歷 for(Integer number : arrayList){System.out.print(number + " "); } 遍歷ArrayList時,通過索引值遍歷效率最高,for循環遍歷次之,迭代器遍歷最低 4、toArray用法有時候,當我們調用ArrayList中的 toArray(),可能遇到過拋出java.lang.ClassCastException異常的情況,這是由于toArray() 返回的是 Object[] 數組,將 Object[] 轉換為其它類型(如,將Object[]轉換為的Integer[])則會拋出java.lang.ClassCastException異常,因為Java不支持向下轉型。?
所以一般更常用的是使用另外一種方法進行使用:
<T> T[] toArray(T[] a) 調用toArray(T[] a)返回T[]可通以下方式進行實現: // toArray用法// 第一種方式(最常用)Integer[] integer = arrayList.toArray(new Integer[0]);// 第二種方式(容易理解)Integer[] integer1 = new Integer[arrayList.size()];arrayList.toArray(integer1);// 拋出異常,java不支持向下轉型//Integer[] integer2 = new Integer[arrayList.size()];//integer2 = arrayList.toArray(); ArrayList<Integer> a = new ArrayList<Integer>();5、用法示例
import java.util.ArrayList; import java.util.Iterator;public class ArrayListDemo {public static void main(String[] srgs){ArrayList<Integer> arrayList = new ArrayList<Integer>();System.out.printf("Before add:arrayList.size() = %d\n",arrayList.size());arrayList.add(1);arrayList.add(3);arrayList.add(5);arrayList.add(7);arrayList.add(9);System.out.printf("After add:arrayList.size() = %d\n",arrayList.size());System.out.println("Printing elements of arrayList");// 三種遍歷方式打印元素// 第一種:通過迭代器遍歷System.out.print("通過迭代器遍歷:");Iterator<Integer> it = arrayList.iterator();while(it.hasNext()){System.out.print(it.next() + " ");}System.out.println();// 第二種:通過索引值遍歷System.out.print("通過索引值遍歷:");for(int i = 0; i < arrayList.size(); i++){System.out.print(arrayList.get(i) + " ");}System.out.println();// 第三種:for循環遍歷System.out.print("for循環遍歷:");for(Integer number : arrayList){System.out.print(number + " ");}// toArray用法// 第一種方式(最常用)Integer[] integer = arrayList.toArray(new Integer[0]);// 第二種方式(容易理解)Integer[] integer1 = new Integer[arrayList.size()];arrayList.toArray(integer1);// 拋出異常,java不支持向下轉型//Integer[] integer2 = new Integer[arrayList.size()];//integer2 = arrayList.toArray();System.out.println();// 在指定位置添加元素arrayList.add(2,2);// 刪除指定位置上的元素arrayList.remove(2); // 刪除指定元素arrayList.remove((Object)3);// 判斷arrayList是否包含5System.out.println("ArrayList contains 5 is: " + arrayList.contains(5));// 清空ArrayListarrayList.clear();// 判斷ArrayList是否為空System.out.println("ArrayList is empty: " + arrayList.isEmpty());} } /** Before add:arrayList.size() = 0 After add:arrayList.size() = 5 Printing elements of arrayList 通過迭代器遍歷:1 3 5 7 9 通過索引值遍歷:1 3 5 7 9 for循環遍歷:1 3 5 7 9 ArrayList contains 5 is: true ArrayList is empty: true */6、ArrayList源碼解析
package java.util;public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable {// 序列版本號private static final long serialVersionUID = 8683452581122892189L;// 默認容量大小private static final int DEFAULT_CAPACITY = 10;// 空數組private static final Object[] EMPTY_ELEMENTDATA = {};// 用于保存ArrayList中數據的數組private transient Object[] elementData;// ArrayList中所包含元素的個數private int size;// 帶初始容量參數的構造函數public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity];}// 默認構造函數,其默認初始容量為10public ArrayList() {super();this.elementData = EMPTY_ELEMENTDATA;}// 帶Collection參數的構造函數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++;if (size < elementData.length) {elementData = Arrays.copyOf(elementData, size);}}// 如有必要,增加此 ArrayList 實例的容量,以確保它至少能夠容納最小容量參數所// 指定的元素數public void ensureCapacity(int minCapacity) {int minExpand = (elementData != EMPTY_ELEMENTDATA)// any size if real element table? 0// larger than default for empty table. It's already supposed to be// at default size.: DEFAULT_CAPACITY;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}private void ensureCapacityInternal(int minCapacity) {if (elementData == EMPTY_ELEMENTDATA) {minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity);}private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;private void grow(int minCapacity) {// overflow-conscious codeint 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);}private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}// 返回ArrayList中的元素個數public int size() {return size;}// 判斷ArrayList是否為空public boolean isEmpty() {return size == 0;}// 判斷ArrayList是否包含Object(o)public boolean contains(Object o) {return indexOf(o) >= 0;}// 返回ArrayList中首次出現的指定元素的索引,或如果此列表不包含元素,則返回 -1public 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中最后一次出現的指定元素的索引,或如果此列表不包含索引,則返回 -1public 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;}// 返回此 ArrayList 實例的淺表副本public Object clone() {try {@SuppressWarnings("unchecked")ArrayList<E> v = (ArrayList<E>) super.clone();// 將當前ArrayList的全部元素拷貝到v中v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError();}}// 按適當順序(從第一個到最后一個元素)返回包含此列表中所有元素的數組public Object[] toArray() {return Arrays.copyOf(elementData, size);}// 返回ArrayList的模板數組。所謂模板數組,即可以將T設為任意的數據類型@SuppressWarnings("unchecked")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;}// 位置訪問操作 @SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}// 返回ArrayList中指定位置上的元素public E get(int index) {rangeCheck(index);return elementData(index);}// 用指定的元素替代ArrayList中指定位置上的元素,并返回替代前的元素public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}// 將指定的元素添加到ArrayList的尾部public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}// 將指定的元素插入ArrayList中的指定位置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++;}// 移除ArrayList中指定位置上的元素,并返回該位置上的元素public E remove(int index) {rangeCheck(index);modCount++;E oldValue = elementData(index);int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; // clear to let GC do its workreturn oldValue;}// 移除ArrayList中首次出現的指定元素(如果存在則移除并返回true,否則返回false)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; // clear to let GC do its work}// 移除ArrayList中的所有元素public void clear() {modCount++;// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}// 按照指定 collection 的迭代器所返回的元素順序,// 將該 collection 中的所有元素添加到ArrayList的尾部public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}// 從指定的位置開始,將指定 collection 中的所有元素插入到ArrayList中public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountint 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(不包括)之間的所有元素protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// clear to let GC do its workint newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}// 私有方法,用于范圍檢測private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}// 私有方法,用于add和addAllprivate void rangeCheckForAdd(int index) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size;}// 移除ArrayList中Collection所包含的所有元素public boolean removeAll(Collection<?> c) {return batchRemove(c, false);}// 保留所有ArrayList和Collection共有的元素public boolean retainAll(Collection<?> c) {return batchRemove(c, true);}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 workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;}// java.io.Serializable的寫入函數// 將ArrayList的“容量,所有的元素值”都寫入到輸出流中private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();// Write out size as capacity for behavioural compatibility with clone()s.writeInt(size);// 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();}}// java.io.Serializable的讀取函數:根據寫入方式讀出// 先將ArrayList的“容量”讀出,然后將“所有的元素值”讀出private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;// Read in size, and any hidden stuffs.defaultReadObject();// Read in capacitys.readInt(); // ignoredif (size > 0) {// be like clone(), allocate array based upon size not capacityensureCapacityInternal(size);Object[] a = elementData;// Read in all elements in the proper order.for (int i=0; i<size; i++) {a[i] = s.readObject();}}}// 返回一個從指定位置開始遍歷的ListIterator迭代器public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}// 返回一個ListIterator迭代器public ListIterator<E> listIterator() {return new ListItr(0);}// 返回一個Iterator迭代器public Iterator<E> iterator() {return new Itr();}// 返回一個指定范圍的子List列表public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, 0, fromIndex, toIndex);} }總結
以上是生活随笔為你收集整理的java中ArrayList用法详解,基本用法(含增删改查)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: activiti5第三弹--------
- 下一篇: 如何在vmvare vsphere(ES