在 Java 未進化到 Java 7 之前, 對於較複雜的集合泛型宣告, 必須重複無謂的聲明句, Google Collections 簡化了其做法, 且只要在 1.5 以上即可使用, 若再配合靜態裝載(import static), 就更佳易讀性. package org.wisdomfish.gcollects;
import static com.google.common.collect.Maps.newHashMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author WisdomFish.ORG
*/
public class MapsDemo {
public static void main(String[] args) {
Map<String, Map<Long, List<String>>> map =
new HashMap<String, Map<Long, List<String>>>();
Map<String, Map<Long, List<String>>> hashmap = newHashMap();
}
}
上述例子同樣可以適用於 List, Set import com.google.common.collect.Lists; import com.google.common.collect.Sets; ...
Lists.newArrayList();
Sets.newHashSet();
接受不可變協議
使用靜態工廠方法或程序是因為實作工具沒有公開的構造子。在很多場合下並我們並不期望創建子類別,因為這要求子類接受不可變協議。 import java.util.*;
import com.google.common.collect.*;
...
HashSet<String> hashSet = Sets.newHashSet();
LinkedHashSet<String> linkedHashSet = Sets.newLinkedHashSet();
ArrayList<String> arrayList = Lists.newArrayList();
LinkedList<String> linkedList = Lists.newLinkedList();
|