package org.maachang.rimdb.util ;

import java.util.Arrays;

/**
 * 数字リスト.
 * 
 * @version 2014/06/29
 * @author  masahito suzuki
 * @since   rimdb-1.00
 */
public final class NList implements NAdd {
    private static final int DEF = 16 ;
    public int[] list ;
    public int length ;
    private int max ;
    
    public NList() {
        this( DEF ) ;
    }
    
    public NList( int buf ) {
        if( buf < DEF ) {
            buf = DEF ;
        }
        max = buf ;
        list = new int[ buf ] ;
        length = 0 ;
    }
    
    public NList( int[] n ) {
        list = n ;
        length = n.length ;
        max = length ;
    }
    
    public final void clear() {
        if( list.length != max ) {
            list = new int[ max ] ;
        }
        length = 0 ;
    }
    
    public final void clear( int buf ) {
        if( list.length < buf ) {
            list = new int[ buf ] ;
        }
        length = 0 ;
    }
    
    public final void add( int n ) {
        if( length + 1 >= list.length ) {
            //int[] tmp = new int[ ( length + ( length >> 1 ) ) + 2 ] ;
            int[] tmp = new int[ length << 1 ] ;
            System.arraycopy( list,0,tmp,0,length ) ;
            list = tmp ;
        }
        list[ length ++ ] = n ;
    }
    
    public final void set( int no,int n ) {
        list[ no ] = n ;
    }
    
    public final int get( int no ) {
        return list[ no ] ;
    }
    
    public final void remove( int no ) {
        if( length > 1 ) {
            for( length -- ; no < length ; list[ no ] = list[ ++ no ] ) ;
        }
        else {
            length = 0 ;
        }
    }
    
    public final int size() {
        return length ;
    }
    
    public final NList sort() {
        if( length > 0 ) {
            Arrays.sort( list,0,length ) ;
        }
        return this ;
    }
    
    public final int[] getArray() {
        int[] ret = new int[ length ] ;
        System.arraycopy( list,0,ret,0,length ) ;
        return ret ;
    }
    
    public final int[] toArray() {
        return list ;
    }
    
    public final void setAll( int[] n ) {
        list = n ;
        length = n.length ;
        max = length ;
    }
}

