Constant Map, constant List in Java

To declare constants in Java, we generally use the final keyword to modify, but final is generally only valid for basic data types, such as:

public static final String content = "你好";
public static final int num = 1;

If we need a constant List or Map, simply using final to modify it will have no effect on adding and modifying the contents of the collection. The following code does not achieve our goal of "constantization of collection content".

    public static final Map<String, String> myMap = new HashMap<String, String>() {
        private static final long serialVersionUID = 1L;

        {
            put("1", "11");
            put("2", "22");
        }
    };

    public static final List<String> myList = new ArrayList<String>() {
        private static final long serialVersionUID = 1L;

        {
            add("a");
            add("b");
        }
    };

If you are interested in specific reasons, you can study Java's memory address storage. The following directly gives the method that can solve the problem and achieve the goal:

    public static final Map<String, String> myMap = Collections.unmodifiableMap(new HashMap<String, String>() {
        private static final long serialVersionUID = 1L;

        {
            put("1", "11");
            put("2", "22");
        }
    });

    public static final List<String> myList = Collections.unmodifiableList(new ArrayList<String>() {
        private static final long serialVersionUID = 1L;

        {
            add("a");
            add("b");
        }
    });

 Of course, List has another method:

public static final List<String> myList1 = new ArrayList<String>(Arrays.asList("Tom", "Jerry", "Mike"));

Finally, one more thing, although the final in the above code does not play a practical role in modifying the contents of Map and List, it is the same as the String type, which prohibits direct assignment to the map. After being modified by final, when our collection is initialized, then direct object assignment, such as  myMap = new HashMap<String, String>();,  cannot be compiled. Therefore, in order to achieve the goal, we must not only prohibit the object from being modified by "direct assignment", but also prohibit the change of the collection content.

Guess you like

Origin blog.csdn.net/ElendaLee/article/details/127260987