ArrayList常用功能底层实现:
private int[] arr;
private int size;
public ArrayList() {
arr=new int[10];
}
public int size() {
return size;
}
public ArrayList(int count) {
if (count < 0) {
throw new RuntimeException("数组的空间长度不能为负数!" + count);
} else {
this.arr = new int[count];
}
}
public void add(int value) {
if (size == arr.length) {
int[] newArray = new int[size + 3];
System.arraycopy(arr, 0, newArray, 0, size);
arr = newArray;
}
arr[size]=value;
size++;
}
public int get(int index) {
if(index<0 || index>=size){
throw new IndexOutOfBoundsException("索引越界异常:" + index);
}
else
return arr[index];
}
public void insert(int index, int value) {
if(index<0 || index>size){
throw new IndexOutOfBoundsException("索引越界异常:" + index);
}
if (size == arr.length) {
int[] newArray = new int[size + 3];
System.arraycopy(arr, 0, newArray, 0, size);
arr = newArray;
}
for(int j=size-1;j>=index;j--){
arr[j+1]=arr[j];
}
arr[index]=value;
size++;
}
public int deleteElementWithIndex(int index) {
if(index<0 || index>=size){
throw new IndexOutOfBoundsException("索引越界异常:" + index);
}
int oldIndex=arr[index];
for(int i=0;i<arr.length-1;i++){
arr[i]=arr[i+1];
}
arr[size-1]=0;
size--;
return oldIndex;
}
测试类:
public static void main(String[] args) {
ArrayList a=new ArrayList();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
for(int i = 0; i < a.size(); i++) {
System.out.print(a.get(i)+" ");
}
System.out.println("\n"+a.size());
a.insert(2, -7);
a.deleteElementWithIndex(1);
for(int i = 0; i < a.size(); i++) {
System.out.print(a.get(i)+" ");
}
}