Java 程序設計語言當中沒有專門的Collection literal語法, 所以, 如果創建一個Collection對象並同時爲其添加一定數量的成員需要很多代碼。
解決這一窘境的變通方法是提供一個vararg collection factory method, 用來創建或列舉出Collection當中包含的成員。
如下:
構造一個Collection的原始的做法是:
Set<String> fruit = new Hash Set<String>();
fruit.add("banana");
fruit.add("pear");
fruit.add("apple");
doSomethingWith(fruit);
我們可以創建一個Vararg collection factory 來簡化這一個過程:
<T> Set<T> setOf(T... strings) {
return new HashSet<T> (Arrays.asList(strings));
}
doSomethingWith(setOf("a", "b", "c"));
參考DoubleBraceInitialisation java idiom.