手写实现Java ArrayList实现
只是实现了一些常用的方法 例如 add() get() set() remove()方法。
都有注释 方便同学们理解代码。
ArrayList的核心是 数组拷贝System.arraycopy()方法。
package collection;
/**
* 手写实现ArrayList方法
* @author Gz
*
*/
public class ArrayListDemo {
private Object [] elementDate;
private int size;
public int size(){
return size;
}
public ArrayListDemo(){
this(10);//默认数组长度为10
}
public ArrayListDemo(int initialCapacity){
if( initialCapacity<0){//如果长度小于0则抛出异常否则把数组的值赋给Object数组
throw new IllegalArgumentException("数组长度小于0"+initialCapacity);
}
this.elementDate=new Object[initialCapacity];
}
public void add(Object obj){
addLength();
elementDate[size]=obj;
size++;
}
public void add(int index,Object o){
//在制定索引位置插入元素 还是用拷贝数组方法实现
RangeCheck(index);
addLength();
System.arraycopy(elementDate, index, elementDate, index+1, size-index);
elementDate[index]=o;
size++;
}
public boolean isEmpty(){
//size等于0 则返回true
return size==0;
}
public Object get(int index){
RangeCheck(index);
return elementDate[index];
}
public boolean remove(int index){
RangeCheck(index);
int numMoved =size-index-1;
if(numMoved>0){
System.arraycopy(elementDate, index+1, elementDate, index, numMoved);//例如:数组中有5个元素 要删掉第3个 则是 把原来的数组中 3+1的位置以后的数组都拷考过 从3个的元素的地方都覆盖掉。
elementDate[size--]=null;//考过来后把原数组最后一个位置等于null
return true;
}
return false;
}
public boolean remove(Object o){
//遍历list如果equals相等则调用remove方法进行删除
for(int i=0;i<size;i++){
if(o.equals(elementDate[i])){
remove(i);
return true;
}
}
return false;
}
public Object set(int index,Object o){
//set方法 传入索引位置和要替换的值 直接替换即可
RangeCheck(index);
Object oldValue=elementDate[index];
elementDate[index]=o;
return oldValue;
}
/**
* 添加方法 如果容量超出 就先扩容(使用数组拷贝方式)再添加
*/
private void addLength(){
if(size==elementDate.length){
Object[] newArray=new Object[size*3/2+1];
System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
elementDate=newArray;
}
}
/**
*查询索引是否越界
*/
private void RangeCheck (int index){
if(index>=size){
throw new IllegalArgumentException("数组下标越界:"+index);
}
}
public static void main(String args[]){
ArrayListDemo list=new ArrayListDemo(0);
list.add("a");
list.add("b");
list.add("c");
System.out.print(list.size());
System.out.print(list.get(-1));
}
}