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 SxtArrayList private static final int DEFALT_CAPACITY = ;// the initial capacity public LittlePagesArrayList() {
elementData = new Object[DEFALT_CAPACITY];
} public LittlePagesArrayList(int capacity) {// set the capacity of SxtArrayList
if (capacity < ) {
throw new RuntimeException("the capacity is negative");
} else if (capacity == ) {
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 >> )];
// use the system method copy the array
System.arraycopy(elementData, , newArray, , 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-;
if(numMoved>){
System.arraycopy(elementData, index+, elementData, index, numMoved);
}
elementData[size-]=null;
size--;
} public void removeElement(E element){
/**
* remove by element
*/
Object objElement=(Object)element;
for (int i=;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 < ) {
throw new IndexOutOfBoundsException(
"the index of SxtArrayList is out of Bounds:" + index);
}
} public int size(){
return size;
} public boolean isEmpty(){
return size==;
}
@Override
public String toString() {// the toString method
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i=;i<size;i++) {
sb.append(elementData[i] + ",");
}
sb.setCharAt(sb.length() - , ']');
return sb.toString();
} /**
* test method
*
* @param args
*/
public static void main(String[] args) {
LittlePagesArrayList s1 = new LittlePagesArrayList();
System.out.println(s1.isEmpty());
for (int i = ; i < ; i++) {
s1.add("littlepage"+i);
}
s1.removeElement();
s1.removeElement();
s1.removeElement("littlepage0");
System.out.println(s1.getElement());
System.out.println(s1);
System.out.println(s1.size());
System.out.println(s1.isEmpty());
} }