Difference between the static initializer block and regular static initialization

后端 未结 8 1991
广开言路
广开言路 2021-01-05 12:12

As the title says, what exactly is the difference between

public static String myString = \"Hello World!\";

and

public stat         


        
8条回答
  •  太阳男子
    2021-01-05 12:36

    To continue with what Scott Stanchfield wrote, you can use the Collections.unmodifiableXXX() methods for safety, though libraries like Google Guava may make that less necessary. Consider:

    public static final Map CAPITALS;
    static {
        Map map = new HashMap<>(); //Java 7.
        map.put("NY", "Albany");
        map.put("MD", "Annapolis");
        map.put("VA", "Richmond");
        map.put("CT", "Hartford");
        // 46 more states
        CAPITALS = Collections.unmodifiableMap(map);
    }
    

    Of course, having a 52-line static block may be disorienting, and so you might instead take the static block and turn it into a static method.

    public static final Map CAPITALS = capitals();
    private static Map capitals() {
        Map map = new HashMap<>(); //Java 7.
        map.put("NY", "Albany");
        map.put("MD", "Annapolis");
        map.put("VA", "Richmond");
        map.put("CT", "Hartford");
        // 46 more states
        return Collections.unmodifiableMap(map);
    }
    

    The difference is a matter of style. You might instead just work with a database table.

提交回复
热议问题