從頭部
,沒有測試:
import java.util.HashMap;
public class MapBuilder<K, E> {
private HashMap<K, E> m_hashMap;
public static HashMap newHashMap(Class<K> keyClass, Class<E> elementClass) {
return new MapBuilder<K, E>();
}
public MapBuilder() {
m_hashMap = new HashMap<K, E>();
}
public MapBuilder with(K key, E element) {
m_hashMap.put(key, element);
return this;
}
public HashMap<K, E> build() {
return m_hashMap;
}
}
用法:
HashMap<String, Integer> myMap = MapBuilder.newHashMap(String.class, Integer.class)
.with("key1", 10)
.with("key2", 20)
.with("key3", 30)
.build();
@Roman關於雙括號的方式 - 這是匿名類的定義和您所呼叫的put()的初始化塊(第二對大括號)。我不喜歡這種方法,因爲它通常會產生有關丟失serialVersionUID的警告,並且您需要@supressWarnings(「serial」)。 – altanis 2012-01-16 11:31:46
請參閱[Guava的ImmutableMap.Builder](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.Builder.html)。對於像這樣的小地圖,還可以看到更方便的[ImmutableMap.of](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html#method_summary )。 – 2013-01-11 22:37:37