Java6学习笔记——ArrayList类的学习

在编程中经常会碰到需要动态操作的数组,比如在运行时增加和删除数组元素,而且有时在编译时又不想确定数组大小希望它可以动态伸缩,在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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值