Effective Java-创建和销毁对象

1、考虑用静态工厂方法代替构造器

public class Beyond {
    public static <K, V> HashMap<K, V> newInstance() {
        return new HashMap<K, V>();
    }

    public static void main(String[] args) {
        HashMap, String> hashMap = Beyond.newInstance();
        for (int i = 0; i < 9; i++) {
            hashMap.put("" + i, "" + i + i);
        }
        System.out.println(hashMap);
        System.out.println("----------------");
        HashMap,String> hashMap1 = new HashMap, String>(10);
        for (int i = 0; i < 9; i++) {
            hashMap1.put("" + i, "" + i + i);
        }
        System.out.println(hashMap);
    }
}

你可能感兴趣的:(Effective,Java)