ArrayList底层实现
2016-04-06 23:02
330 查看
package com.scxh.ex11list.arrayList;
import java.util.ArrayList;
import java.util.Arrays;
public class MyArrayList{
private Object[] obj;
private int size; //元素的个数
public MyArrayList(){
this(4);
}
public MyArrayList(int initialCapacity){
this.obj=new Object[initialCapacity];
}
//添加元素
public void add(Object element){
if(obj.length<=size){
Object[] newObj=new Object[obj.length*2];
System.arraycopy(obj, 0, newObj, 0, size);
obj=newObj;
}
obj[size]=element;
size++;
}
//将元素添加到index下标处
public void add(int index,Object element){
if(obj.length<=size){
Object[] newObj=new Object[obj.length*2];
System.arraycopy(obj, 0, newObj, 0, size);
obj=newObj;
}
System.arraycopy(obj, index, obj, index+1, size-index);
obj[index]=element;
size++;
}
//移除下标为index处的元素
public Object remove(int index){
Object oldvalue=obj[index];
System.arraycopy(obj, index+1, obj, index, size-1-index);
size--;
return oldvalue;
}
//移除数组中元素为element的元素
public void remove(Object element){
for(int i=0;i<size;i++){
Object o=obj[i];
if(o.equals(element)){
this.remove(i);
break;
}
}
}
//获取数组长度
public int size(){
return size;
}
//获取下标为index处的元素
public Object get(int index){
return obj[index];
}
}