在编程中经常会碰到需要动态操作的数组,比如在运行时增加和删除数组元素,而且有时在编译时又不想确定数组大小希望它可以动态伸缩,在Java中解决这一问题的方法是使用java.util包中的ArrayList类,该类提供了许多的方法可以实现数组的动态操控。如果试图给ArrayList类添加走出容量允许范围的对象数,它会自动增大,新增的内在区域是当前容量两倍的元素,并重新定位这些元素。
简而言之,ArrayList类是List的可变数组的实现。
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest
{
private static final String[] colors =
{ "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
private static final String[] removeColors =
{ "RED", "WHITE", "BLUE" };
// create ArrayList, add Colors to it and manipulate it
public CollectionTest()
{
List< String > list = new ArrayList< String >();
List< String > removeList = new ArrayList< String >();
// add elements in colors array to list
for ( String color : colors )
list.add( color );
// add elements in removeColors to removeList
for ( String color : removeColors )
removeList.add( color );
System.out.println( "ArrayList: " );
// output list contents
for ( int count = 0; count < list.size(); count++ )
System.out.printf( "%s ", list.get( count ) );
// remove colors contained in removeList
removeColors( list, removeList );
System.out.println( "/n/nArrayList after calling removeColors: " );
// output list contents
for ( String color : list )
System.out.printf( "%s ", color );
System.out.println();
} // end CollectionTest constructor
// remove colors specified in collection2 from collection1
private void removeColors(
Collection< String > collection1, Collection< String > collection2 )
{
// get iterator
Iterator< String > iterator = collection1.iterator();
// loop while collection has items
while ( iterator.hasNext() )
if ( collection2.contains( iterator.next() ) )
iterator.remove(); // remove current Color
} // end method removeColors
public static void main( String args[] )
{
new CollectionTest();
} // end main
} // end class CollectionTest
输出:
ArrayList:
MAGENTA RED WHITE BLUE CYAN
ArrayList after calling removeColors:
MAGENTA CYAN