Java中顺序表存储ID的设计

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DT_Zhangshuo/article/details/82876459

我定义了一个ArrayId类,内部封装了一个数组和对数组的操作方法。
主要实现了数组的自动扩容,注册时返回一个没有空的id,前面如果有空位置优先前面的,对空位做记录,牺牲部分空间来提高执行效率。
下图size就是实际存储的大小,size和end之间是曾经删除过的记录。
这是一个解释图


public class ArrayId<E> implements Serializable {
    Object obs[];
    private int realsize;
    private int size;//实际存值的最后一个位置
    private int end;//记录空缺的最后位置

    ArrayId(){
        realsize=64;
        obs=new Object[realsize];
    }

    public synchronized int add(Object o){//传入对象并且返回对象最后存放的位置
        int index=0;
        if(obs[size]==null){
            obs[size]=o;
            index=size;
            size++;
            end++;
            if(size*2>realsize){//如果存储数据超过数组的一半就扩大数组为原来的两倍
                realsize*=2;
                Object obs2=obs;
                obs=new Object[realsize];
                System.arraycopy(obs2,0,obs,0,realsize);
            }
        }else{
            index=(int)obs[end-1];
            obs[index]=o;
            obs[end-1]=null;
            end--;
        }
        return index;
    }

    public synchronized void remove(int index){//移除这个位置的元素,并记录这个位置
        if(index==size-1){
            obs[index]=null;
            obs[index]=obs[end-1];
            obs[end-1]=null;
            size--;
            end--;
        }else{
            obs[index]=null;
            obs[end]=index;
            end++;
        }
    }

    public synchronized E get(int index){
        E o=null;
        if(index>=0&&index<=size)
        o=(E)obs[index];
        return o;
    }

    public synchronized void showall(){
        for(int i=0;i<size;i++){
            if(obs[i]!=null){
                Users u=(Users)obs[i];
                System.out.println("ID"+u.ID+"  用户名"+u.name+"  密码"+u.password);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/DT_Zhangshuo/article/details/82876459