用数组的方式实现ArrayList


/**
 * this is my ArrayList
 * @param <Object>
 */
public class myarraylist<Object> implements Iterable<Object> {

    private static final int DEFAULT_CAPACITY = 10;  //用来定义默认数组的长度
    private int thesize;      //用来控制theitems数组的长度(实际也就是控制myarrarlist的长度)
    private Object[] theitems;  //用object类型来实现一个数组(实际也就是myarraylist)

    public int getThesize() {
        return thesize;
    }

    public void setThesize(int thesize) {
        this.thesize = thesize;
    }

    public myarraylist(){
        clear();
    }
    public void clear(){
        thesize = 0;
        ensureCapacity(DEFAULT_CAPACITY);
    }

    public boolean isEmpty(){
        return size()==0;
    }

    /**
     * 传入一个下标获取对应的值
     * @param index
     * @return
     */
    public Object get(int index){
        if(index<0 || index >=size()){
            throw new IndexOutOfBoundsException();
        }
        return theitems[index];
    }

    public boolean add(Object x){
        add(x,size());
        return true;
    }
    public void trimtosize(){
        ensureCapacity(size());
    }
    public void add(Object x,int index){
        if(size() == theitems.length){
            ensureCapacity(size()*2+1);
        }
        theitems[index] = x;
        thesize++;
    }
    public Object remove(int index){
        Object removeitem = get(index);
        for(int i=index;i<size();i++){
            theitems[i] = theitems[i+1];
        }
        thesize--;
        return removeitem;
    }


    private void ensureCapacity(int newCapacity) {
        Object[] old = theitems;
        theitems = (Object[]) new java.lang.Object[newCapacity];
        if(newCapacity < thesize){
            for(int i=0;i<newCapacity;i++){
                theitems[i] = old[i];
            }
        }

        for(int i=0;i<size();i++){
            theitems[i] = old[i];
        }

    }

    private int size() {
        return thesize;
    }
    public Iterator<Object> iterator(){
        return new ArrayListIterator();
    }






    @Override
    public void forEach(Consumer<? super Object> action) {

    }

    @Override
    public Spliterator<Object> spliterator() {
        return null;
    }
    public class ArrayListIterator implements Iterator<Object> {
        private int current = 0;

        @Override
        public boolean hasNext() {
            return current<size();
        }

        @Override
        public Object next() {
            if(!hasNext()){
                throw new IndexOutOfBoundsException();
            }

            return theitems[current++];
        }


        @Override
        public void remove() {
            myarraylist.this.remove(--current);
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值