java实现ArrayList

java实现ArrayList

认识ArrayList

ArrayList继承自AbstractList 并实现List接口。

  • arrayList可以存放null
  • arrayList本质上就是一个elementData数组
  • arrayList区别于数组的地方在于能够自动扩展大小,其中关键的方法就是gorw()方法
  • arrayList中removeAll(Collection c)和clear()的区别就是removeAll可以删除批量指定的元素,而clear是全是删除集合中的元素
  • arrayList由于本质是数组,所以它在数据的查询方面会很快,而在插入删除这些方面,性能下降很多,有移动很多数据才能达到应有的效果
  • ArrayList的用法和Vector的区别是:ArrayList是线程不安全的,当多条线程访问同一个ArrayList集合时,程序需要手动保证该集合的同步性,而Vector则是线程安全的。

代码实现:

public class ArrayListTest<T> {

    private Object[] elementData;
    private int size;
public ArrayListTest(int cap){
    if (cap<0)
        throw new IllegalArgumentException();
    this.elementData=new Object[cap];
}
    /**
     * 添加元素
     */
    public boolean add(T value) {
        if (size==elementData.length){

         elementData = Arrays.copyOf(elementData,elementData.length*2);
            }
            elementData[size++]=value;
        return true;

    }

    /**
     * 获取元素
     */
    public T get(int index) {
        if (!checkRange(index)) {
            throw new IndexOutOfBoundsException("参数越界");
        }
        return (T) elementData[index];

    }

private boolean checkRange(int index) {
    if (index < 0 || index >= size) {
        return false;

    }
    return true;
}

    /**
     * 获取元素个数
     */
    public int size() {
        if (elementData.length==0){
            return 0;
        }
        return size;
    }

    /**
     * 删除元素
     */
    public T remove(int index) {
      if (!checkRange(index)){
         throw new IndexOutOfBoundsException("");
      }
      T oldvalue= (T) elementData[index];
       System.arraycopy(elementData,index+1,elementData,index,size-index-1);
       elementData[size-1]=null;
       --size;
       return oldvalue;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值