基于JDK5.0一些collection類的使用總結

發表于:2008-06-03來源:作者:點擊數: 標簽:collection
關鍵字: 在5.0中,collection最大的一個改變就是可以指定它的具體類型: List list=new List; 兩個最基本的接口: public interface Collection { boolean add(E element); Iterator iterator(); . . . } public interface Iterator { E next(); boolean has
關鍵字:


在5.0中,collection最大的一個改變就是可以指定它的具體類型:
List list=new List;

兩個最基本的接口:
public interface Collection
{
boolean add(E element);
Iterator iterator();
. . .
}

public interface Iterator
{
E next();
boolean hasNext();
void remove();
}

在5.0以前,常用的形式就是:
Collection c = . . .;
Iterator iter = c.iterator();
while (iter.hasNext())
{
String element = iter.next();
do something with element
}
但是在5.0中加入另外一種循環方式,類似于for each:
for (String element : c)
{
do something with element
}
這種方式對任何實現了Iterable接口的類都適用。

在使用remove的時候特別要注意的一點是,在調用remove之前必須先調用一次next方法,因為next就像是在移動一個指針,remove刪掉的就是指針剛剛跳過去的東西。即使是你想連續刪掉兩個相鄰的東西,也必須在每次刪除之前調用next。

對collection排序和查找
Collections類的sort方法可以對任何實現了List接口的類進行排序。在排序過程中,他默認這些類實現了Comparable接口,如果想用其他方法排序,可以在調用sort方法的時候提供一個Comparator對象:
Comparator itemComparator = new
Comparator()
{
public int compare(Item a, Item b)
{
return a.partNumber - b.partNumber;
}
});
反向排序:
Collections.sort(items, itemComparator);
Collections.sort(items, Collections.reverseOrder(itemComparator));

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97