java基础---final常犯错误

final关键字:类、方法、变量

    修饰类:不能被继承,详情看String类
    修饰方法:1、锁定方法不被继承类修改;2、效率

    修饰变量:基本数据类型变量不可修改、引用类型变量不能指向其他对象

以下是常犯错误:

package concurrency.example.immutable;

import com.google.common.collect.Maps;
import concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/*
 *Created by William on 2018/4/29 0029
 * final修饰变量
 */
@Slf4j
@NotThreadSafe
public class ImmutableExample1 {
    private final static Integer a = 1;
    private final static String b = "2";
    private final static Map<Integer, Integer> map = Maps.newHashMap();

    static {
        map.put(1, 2);
        map.put(3, 4);
        map.put(5, 6);
    }

    public static void main(String[] args) {
//        a=2;  编译报错
//        b="3";编译报错
//        map = Maps.newHashMap();编译报错
        map.put(1, 3);
        log.info("map:{}", map.get(1));
    }
}
final修饰map之后,数值还是可以修改的,只是不能指向其他对象。

猜你喜欢

转载自blog.csdn.net/weianluo/article/details/80144084