手写实现Java ArrayList实现

手写实现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));

 }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值