final修饰的变量

2019-10-14  本文已影响0人  不知名的蛋挞

final的作用

实战演示

public class FinalDemo {
    private static final Map<String, Object> NAME = new HashMap<>(16);
    private static final List<String> LIST = new ArrayList<>(10);
    private static final String[] TYPE = new String[15];
    private static final StringBuilder SB = new StringBuilder("22");
    private static final StringBuffer SBU = new StringBuffer("22");
    private static final String S = "44";
    private static final int num = 44;
    private static final String S1 = new String();

    public void setName() {
        NAME.put("1", "maomao");
        LIST.add("11");
        TYPE[0] = "1";
        SB.append("12");
        SBU.append("32");
        System.out.println(NAME);
        System.out.println(LIST);
        System.out.println(Arrays.asList(TYPE));
        System.out.println(SB.toString());
        System.out.println(SBU.toString());
    }

    public static void main(String[] args) {
        FinalDemo finalDemo = new FinalDemo();
        finalDemo.setName();
    }
}

运行结果:

{1=maomao}
[11]
[1, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
2212
2232

由此可见:

所以被final修饰的变量,不可变的是变量的引用,而不是变量的内容。

上一篇下一篇

猜你喜欢

热点阅读