代码实现
package top. gldwolf. java. datastructure. lineartable;
public class LinearTable < T> { private static final int INITIAL_SIZE = 20 ; private Object[ ] data = null; private int length; private int cursor = 0 ; public LinearTable ( ) { data = new Object [ INITIAL_SIZE] ; this . length = INITIAL_SIZE; } public LinearTable ( int size) { data = new Object [ size] ; this . length = size; } public int length ( ) { return this . length; } public T get ( int index) throws Exception { if ( index <= 0 || index > data. length) { throw new Exception ( "下标越界" ) ; } return ( T) data[ index - 1 ] ; } public boolean append ( T data) { try { this . data[ cursor] = data; cursor++ ; return true ; } catch ( Exception e) { return false ; } } public boolean insert ( int index, T data) throws Exception { if ( index <= 0 || index > length || cursor > length - 1 || this . data[ index - 1 ] != null) { throw new Exception ( "下标越界或线性表已满!" ) ; } else if ( index == length) { this . data[ index - 1 ] = data; cursor ++ ; return true ; } else { for ( int i = cursor; i >= index - 1 ; i-- ) { this . data[ i + 1 ] = this . data[ i] ; } this . data[ index - 1 ] = data; this . cursor++ ; return true ; } } public boolean delete ( int index) throws Exception { if ( index <= 0 || index > length) { throw new Exception ( "下标越界!" ) ; } else if ( index == length) { data[ index - 1 ] = null; return true ; } else { for ( int i = index - 1 ; i < length - 1 ; i++ ) { data[ i] = data[ i + 1 ] ; } data[ length - 1 ] = null; return true ; } } @Override public String toString ( ) { StringBuffer res = new StringBuffer ( ) ; for ( Object t : data) { res. append ( t + ", " ) ; } return res. toString ( ) ; }
}
测试类
package top. gldwolf. java. datastructure. lineartable; public class LinearTableDriver { public static void main ( String[ ] args) throws Exception { LinearTable< String> table = new LinearTable < > ( 5 ) ; table. append ( "hello" ) ; table. append ( "world" ) ; table. append ( "you" ) ; System. out. println ( table. toString ( ) ) ; table. insert ( 2 , "good" ) ; System. out. println ( "------------" ) ; System. out. println ( table. toString ( ) ) ; System. out. println ( "------------" ) ; table. insert ( 5 , "last" ) ; System. out. println ( table. toString ( ) ) ; table. delete ( 5 ) ; System. out. println ( table. toString ( ) ) ; table. delete ( 2 ) ; System. out. println ( table. toString ( ) ) ; }
}