JAVA SE ArrayList 底層實現
阿新 • • 發佈:2019-01-25
boolean init capacity 安全 string time char rgs @override
Array 查詢效率高,增刪效率低(
Link 增刪效率高
Vector 線程安全
List 列表
源代碼:
package com.littlepage.test; /** * 基於底層實現ArrayList * @author Littlepage * @reference bjsxt.com */ public class LittlePagesArrayList<E> { // the array of element private Object[] elementData; private int size;// the size of SxtArrayListprivate static final int DEFALT_CAPACITY = 10;// the initial capacity public LittlePagesArrayList() { elementData = new Object[DEFALT_CAPACITY]; } public LittlePagesArrayList(int capacity) {// set the capacity of SxtArrayList if (capacity < 0) { throw newRuntimeException("the capacity is negative"); } else if (capacity == 0) { elementData = new Object[DEFALT_CAPACITY]; } else { elementData = new Object[capacity]; } } public void add(E element) { if (elementData.length == size) {/** * enlarge the capacity by 1.5 times **/ Object[] newArray = new Object[elementData.length + (elementData.length >> 1)]; // use the system method copy the array System.arraycopy(elementData, 0, newArray, 0, elementData.length); elementData = newArray; } elementData[size++] = element; } public E getElement(int index) { checkRange(index); return (E) elementData[index];// get element by index } public void setElement(int index, E element) { /** * set element by index */ checkRange(index); elementData[index] = element; } public void removeElement(int index) { /** * remove by index */ int numMoved=elementData.length-index-1; if(numMoved>0){ System.arraycopy(elementData, index+1, elementData, index, numMoved); } elementData[size-1]=null; size--; } public void removeElement(E element){ /** * remove by element */ Object objElement=(Object)element; for (int i=0;i<size;i++) { if(objElement.equals(elementData[i])){ removeElement(i);//remove by index } } } public void checkRange(int index) { /** * check the index range */ if (index >= size || index < 0) { throw new IndexOutOfBoundsException( "the index of SxtArrayList is out of Bounds:" + index); } } public int size(){ return size; } public boolean isEmpty(){ return size==0; } @Override public String toString() {// the toString method StringBuilder sb = new StringBuilder(); sb.append("["); for (int i=0;i<size;i++) { sb.append(elementData[i] + ","); } sb.setCharAt(sb.length() - 1, ‘]‘); return sb.toString(); } /** * test method * * @param args */ public static void main(String[] args) { LittlePagesArrayList s1 = new LittlePagesArrayList(20); System.out.println(s1.isEmpty()); for (int i = 0; i < 32; i++) { s1.add("littlepage"+i); } s1.removeElement(6); s1.removeElement(5); s1.removeElement("littlepage0"); System.out.println(s1.getElement(5)); System.out.println(s1); System.out.println(s1.size()); System.out.println(s1.isEmpty()); } }
JAVA SE ArrayList 底層實現