所以,如何去選擇還是取決于實際的使用情況。你需要考慮下面幾個問題。你的程序是插入/刪除的操作多,還是查找的操作多?數組里最多可能存儲多少元素?排序的頻率是多少?以及你的性能基準測試的結果是怎樣的?
Q:怎么實現一個不可變集合?
A:這個功能在Collections類里實現了,它通過裝飾模式實現了對一般集合的封裝。
1
2
3
4
5
6
7
8
9
10
11
|
public class ReadOnlyExample { public static void main(String args[ ]) { Set<string> set = new HashSet<string>( ); set.add( "Java" ); set.add( "JEE" ); set.add( "Spring" ); set.add( "Hibernate" ); set = Collections.unmodifiableSet(set); set.add( "Ajax" ); // not allowed. } } |
Q:下面的代碼的功能是什么呢?其中的LinkedHashSet能用HashSet來取代嗎?
1
2
3
4
5
6
7
8
9
|
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; public class CollectionFunction { public <e> List<e> function (List <e> list) { return new ArrayList<e>( new LinkedHashSet<e>(list)); } } |
原文轉自:http://www.importnew.com/871.html