public static <K,V> HashMap<K,V> newInstance(){
return new HashMap<K,V>();
}Map<String,List<String>> m = HashMap.newInstance();//如果有了上面的静态工厂方法,就可以利用方法的类型推导,这样定义,他可以推导出K,V分别是String 和 List<String>
//A builder for objects of type Tpublicinterface Builder<T>{
public T build();
}
//比如,可以声明NutritionFacts.Builder类来实现Builder<NutritionFacts>
带有Builder实例的方法通常李勇有限制的通配符类型来约束构建器的类型参数,如:
Tree buildTree(Builder<? extends Node> nodeBuilder){...}
第三条 用私有构造器或枚举类型强化Singleton属性
实现Singleton的几种方法:
通过私有构造器
publicclass Elvis {
publicstatic final Elvis INSTANCE = new Elvis();
privateElvis() {
}
publicvoidleaveTheBuilding() {
System.out.println("Whoa baby, I'm outta here!");
}
// This code would normally appear outside the class!publicstaticvoidmain(String[] args) {
Elvis elvis = Elvis.INSTANCE;
elvis.leaveTheBuilding();
}
}
publicclass Elvis {
privatestatic final Elvis INSTANCE = new Elvis();
privateElvis() {
}
publicstatic Elvis getInstance() {
return INSTANCE;
}
publicvoidleaveTheBuilding() {
System.out.println("Whoa baby, I'm outta here!");
}
// This code would normally appear outside the class!publicstaticvoidmain(String[] args) {
Elvis elvis = Elvis.getInstance();
elvis.leaveTheBuilding();
}
}
publicclass Elvis {
publicstatic final Elvis INSTANCE = new Elvis();
privateElvis() {
}
publicvoidleaveTheBuilding() {
System.out.println("Whoa baby, I'm outta here!");
}
private Object readResolve() {
// Return the one true Elvis and let the garbage collector// take care of the Elvis impersonator.return INSTANCE;
}
// This code would normally appear outside the class!publicstaticvoidmain(String[] args) {
Elvis elvis = Elvis.INSTANCE;
elvis.leaveTheBuilding();
}
}
使用枚举类型
publicenum Elvis {
INSTANCE;
publicvoidleaveTheBuilding() {
System.out.println("Whoa baby, I'm outta here!");
}
// This code would normally appear outside the class!publicstaticvoidmain(String[] args) {
Elvis elvis = Elvis.INSTANCE;
elvis.leaveTheBuilding();
}
}
publicclass Sum {
// Hideously slow program! Can you spot the object creation?publicstaticvoidmain(String[] args) {
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
}
publicclassEmptyStackExceptionextendsIllegalStateException {
}
publicclassStack {private Object[] elements;
privateint size = 0;
privatestaticfinalint DEFAULT_INITIAL_CAPACITY = 16;
publicStack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
publicvoidpush(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
thrownew EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly doubling the capacity
* each time the array needs to grow.
*/privatevoidensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}