LIst与自己动手写ArryList实现类

List中常用的实现类有ArryList、LinkedList和Vector。Vector是线程安全的常用于接收数据库查询后返回数据,当然线程安全就代表速度慢效率低。而ArryList 是线程不安全的,并且其底层实现是采用数组实现的,所以查询快速但是添加,删除慢。LinkedList 是线程不安全的,其底层采用链表实现,所以查询慢但是添加删除块。

自己手写ArryLIst类(简易版)。

public class MyArryList {
    private Object[] value;
    private int size=-1;
    public MyArryList() {
        this(10);
    }    
    public MyArryList(int size) {
        if(size<0)
            try {
                throw new Exception();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         value =new Object[size];
    }
    public void add(Object obj) {
        if(size<(value.length-1)) {
        }
        else
        {
            Object[] newvalue=new Object[size*2+1];
            System.arraycopy(value, 0, newvalue, 0, size);
            value=newvalue;
        }
        size++;
        value[size]=obj;
    }
    public void add(int indext,Object obj) {
        if(indext<0||indext>size)
            throw new ArrayIndexOutOfBoundsException("超出界限!!");
        if(size==(value.length-1)) {
        Object[] newvalue=new Object[size*2+1];
        System.arraycopy(value, 0, newvalue, 0, size);
        value=newvalue;
        }
        size++;
        for(int i=size;i>indext;i--) {
             value[i]=value[i-1];
        }
        value[indext]=obj;
    }
    public Object get(int id) {
        if(id<0||id>size)
                throw new ArrayIndexOutOfBoundsException("超出界限!!");
        
        return value[id]    ;
    }
    public boolean delete(int id) {
        if(id<0||id>size)
                throw new ArrayIndexOutOfBoundsException("超出界限!!");
        else {
        for (int i=id;i<(size-1);i++) {
            value[i]=value[i++];
            
        }
           size--;
        }
        return true;
    }
    public boolean delete(Object obj) {
        if(obj==null) {
             for(int i=0;i<=size;i++) {
                 if(value[i]==null) {
                     delete(i);
                     return true;
                 }
             }
        }else 
         for(int i=0;i<=size;i++) {
             if(value[i].equals(obj)) {
                 delete(i);
                 return true;
             }
         }
        return false;
    }
    public int size() {
        return size+1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35681797/article/details/82083870