package org.maachang.mimdb.core.util ;

/**
 * オブジェクトリスト.
 * 
 * @version 2013/10/26
 * @author masahito suzuki
 * @since MasterInMemDB 1.00
 */
@SuppressWarnings("unchecked")
public class ObjectList<T> {
    private static final int DEF_LENGTH = 8 ;
    private Object[] list ;
    private int length ;
    private int max ;
    
    public ObjectList() {
        this( DEF_LENGTH ) ;
    }
    
    public ObjectList( int buf ) {
        if( buf < DEF_LENGTH ) {
            buf = DEF_LENGTH ;
        }
        max = buf ;
        list = new Object[ buf ] ;
        length = 0 ;
    }
    
    public void clear() {
        if( list.length != max ) {
            list = new Object[ max ] ;
        }
        length = 0 ;
    }
    
    public void add( T n ) {
        if( length + 1 >= list.length ) {
            Object[] tmp = new Object[ length << 1 ] ;
            System.arraycopy( list,0,tmp,0,length ) ;
            list = tmp ;
        }
        list[ length ++ ] = n ;
    }
    
    public void set( int no,T o ) {
        list[ no ] = o ;
    }
    
    public T get( int no ) {
        return (T) list[ no ] ;
    }
    
    public void remove( int no ) {
        if( length > 1 ) {
            for( length -- ; no < length ; list[ no ] = list[ ++ no ] ) ;
            list[ length ] = null ;
        }
        else {
            length = 0 ;
            list[ 0 ] = null ;
        }
    }
    
    public int size() {
        return length ;
    }
    
    public int search( T n ) {
        int len = length ;
        if( n == null ) {
            for( int i = 0 ; i < len ; i ++ ) {
                if( list[ i ] == null ) {
                    return i ;
                }
            }
        }
        else {
            for( int i = 0 ; i < len ; i ++ ) {
                if( n.equals( list[ i ] ) ) {
                    return i ;
                }
            }
        }
        return -1 ;
    }
    
    public Object[] getArray() {
        Object[] ret = new Object[ length ] ;
        System.arraycopy( list,0,ret,0,length ) ;
        return ret ;
    }
}

