선형 표 배열 구현

4511 단어 데이터 구조
/**
 *    ,    
 * @author yuli
 *
 */
public class MyArrayList<T> {
    private static final int DEFAULT_CAPACITY = 10;//    
    private int size;
    private Object[] items;
    public MyArrayList() {
        clean();
    }
    public void clean(){
        this.size=0;
        swap(DEFAULT_CAPACITY);
    }
    public int size(){
        return size;
    }
    /**
     *           
     * @param t
     * @param index
     * @return
     */
    public T set(T t,int index){
        if(index < 0 || index > size){
            throw new ArrayIndexOutOfBoundsException(index);
        }
        @SuppressWarnings("unchecked")
        T old = (T) items[index];
        items[index] = t;
        return old;
    }
    /**
     *         
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    public T get(int index){
        if(index < 0 || index> size){
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return (T) items[index];
    }
    /**
     *          
     * @param t
     */
    public void add(T t){
        if(size == items.length){
            swap(size * 2 + 1);
        }
        items[size++] = t;
    }
    /**
     *           
     * @param t
     * @param index
     */
    public void add(T t,int index){
        if(index < 0 || index> size){
            throw new ArrayIndexOutOfBoundsException(index);
        }
        //                   ,   
        if(size == items.length){
            swap(size * 2 + 1);
        }
        for(int i = size ;i > index;i++){
            items[i] = items[i-1];
        }
        items[index] = t;
        size++;
    }
    /**
     *       
     **
    @SuppressWarnings("unchecked")
    public T remove(int index){
        if(index < 0 || index> size){
            throw new ArrayIndexOutOfBoundsException(index);
        }
        Object item = items[index];
        for(int i = index;i@param newSize
     */
    public void swap(int newSize){
        if(newSize < size){
            return;
        }
        Object[] newItems = new Object[newSize];
        for(int i=0;i<this.size;i++){
            newItems[i]=items[i];
        }
        this.items = newItems;
    }
}

좋은 웹페이지 즐겨찾기