Java中的不可变对象

Java中的不可变对象

一.需要的条件

不可变对象需要满足的条件

  • 对象创建之后其状态就不可改变
  • 对象所有域都是final类型
  • 对象是正确创建的(在对象创建期间,this引用没有逸出)

二.final关键字修饰

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

  • 修饰类:不能被继承
  • 修饰方法:1、锁定方法不被继承类修改;2、效率
  • 修饰变量:基本数据类型变量、引用类型变量

三.其他定义不可变对象的方式

  1. Java中的Collections.unmodifiableXXX
  2. Guava中的ImmutableXXX

四.Example

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 = 5; // 不可重新赋值
//        b = "6"; // 不可重新赋值
//        map = Maps.newHashMap(); // 不可指向另外一个对象
        map.put(7, 8); //
        log.info("{}", map.get(1));
    }
}
public class ImmutableExample2 {

    private final static Map<Integer, Integer> map = Maps.newHashMap();

    static {
        // 可以赋值
        map.put(1, 2);
        map.put(3, 4);
        map.put(5, 6);
//        map = Collections.unmodifiableMap(map); // 不可指向另外一个对象
    }

    public static void main(String[] args) {
        map.put(7, 8);
        log.info("{}", map.get(1));
    }
}
public class ImmutableExample3 {
    private final static ImmutableList list = ImmutableList.of(1, 2, 3);
    private final static ImmutableSet set = ImmutableSet.copyOf(list);
    private final static ImmutableMap map = ImmutableMap.of(1, 2, 3, 4);
    private final static ImmutableMap map2 = ImmutableMap.builder()
            .put(1, 2)
            .put(3, 4)
            .put(5, 6)
            .build();

    public static void main(String[] args) {
        // 不能使用,这里不能操作不可变对象
        list.add(1);
        set.add(1);
        map.put(7,8);
        map2.put(7,8);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值