需求
自定义的MyArrayList
import java. util. Arrays ;
import java. util. Objects ; public class MyArrayList < E > { private Object [ ] elementData ; private int size; private static final int DEFAULT_CAPACITY = 10 ; public boolean add ( E e) { if ( Objects . isNull ( elementData) || size == elementData. length ) { grow ( ) ; } elementData[ size++ ] = e; return true ; } public E get ( int index) { checkIndex ( index) ; return ( E ) elementData[ index] ; } public E remove ( int index) { checkIndex ( index) ; E oldValue = ( E ) elementData[ index] ; int moveSize = size - index - 1 ; if ( moveSize > 0 ) { System . arraycopy ( elementData, index + 1 , elementData, index, moveSize) ; } elementData[ -- size] = null ; return oldValue; } public void forEach ( MyConsumer < E > action) { Objects . requireNonNull ( action) ; for ( int i = 0 ; i < size; i++ ) { action. accept ( ( E ) elementData[ i] ) ; } } private void grow ( ) { if ( size == 0 ) { elementData = new Object [ DEFAULT_CAPACITY ] ; } else { elementData = Arrays . copyOf ( elementData, size + ( size >> 1 ) ) ; } } private void checkIndex ( int index) { if ( index < 0 || index >= size) { throw new IndexOutOfBoundsException ( "索引不合法" ) ; } } @Override public String toString ( ) { StringBuilder sb = new StringBuilder ( ) ; sb. append ( "[" ) ; for ( int i = 0 ; i < size; i++ ) { sb. append ( elementData[ i] ) ; if ( i < size - 1 ) { sb. append ( "," ) ; } } sb. append ( "]" ) ; sb. append ( "size = " ) . append ( size) ; sb. append ( " capacity = " ) . append ( elementData. length) ; return sb. toString ( ) ; }
}
自定义函数式接口(供forEach使用)
@FunctionalInterface
public interface MyConsumer < E > { void accept ( E e) ;
}
测试
MyArrayList < String > list = new MyArrayList < > ( ) ;
list. add ( "张无忌" ) ;
list. add ( "赵敏" ) ;
list. add ( "周芷若" ) ;
list. add ( "小昭" ) ;
list. add ( "殷素素" ) ;
list. add ( "张三丰" ) ;
list. add ( "张翠山" ) ;
list. add ( "张无忌" ) ;
list. add ( "赵敏" ) ;
list. add ( "周芷若" ) ;
list. add ( "小昭" ) ;
System . out. println ( "list = " + list) ;
list. remove ( 0 ) ;
list. remove ( 99 ) ;
System . out. println ( "list = " + list) ;
list. forEach ( System . out:: println ) ;