MyColltion
public class MyCollection {
Object[ ] value;
int size;
public MyCollection ( ) {
this ( 3 ) ;
}
public MyCollection ( int i) {
value = new Object [ i] ;
}
public void add ( Object obj) {
value[ size] = obj;
size++ ;
if ( size > value. length- 1 ) {
Object[ ] newValue = new Object [ value. length<< 1 + 2 ] ;
for ( int i = 0 ; i < value. length; i++ ) {
newValue[ i] = value[ i] ;
}
value = newValue;
}
}
public Object get ( int index) {
if ( index<= 0 || index> size- 1 ) {
throw new IndexOutOfBoundsException ( "数组越界" ) ;
}
return value[ index- 1 ] ;
}
public String toString ( ) {
StringBuilder s = new StringBuilder ( "[" ) ;
for ( int i = 0 ; i < size; i++ ) {
s. append ( value[ i] ) ;
s. append ( "," ) ;
}
s. setCharAt ( s. length ( ) - 1 , ']' ) ;
return s. toString ( ) ;
}
public static void main ( String[ ] args) {
MyCollection myCollection = new MyCollection ( ) ;
myCollection. add ( "123" ) ;
myCollection. add ( "456" ) ;
myCollection. add ( "789" ) ;
myCollection. add ( "101112" ) ;
myCollection. add ( new Student ( "khp" , 123 ) ) ;
System. out. println ( myCollection. toString ( ) ) ;
}
}