Java不可变对象
不可变对象需要满足的条件
- 对象创建以后其状态就不能修改
- 对象所有域都是final类型
- 对象是正确创建的(在对象创建期间,this引用没有逸出)
final 关键字:类,方法,变量
- 修饰类:不能被继承
- 修饰方法:1.锁定方法不被继承类修改(private修饰的方法隐式的被定义成final方法);2.效率
- 修饰变量: 基本数据类型变量,初始化之后就不能更改了,引用类型变量,初始化之后就不能再指向另外一个对象
Collections.unmodifiable、guava的 Immutable**
Collections.unmodifiable、guava的 Immutable** 分别创建不可变对象,并且对象的内部成员变量也不能修改
Collections.unmodifiable**
注意:这里map 不能声明为final
@Slf4j
@ThreadSafe
public class ImmutableExample2 {
private final static Integer a = 1;
private final static String b = "2";
private static Map<Integer, Integer> map = Maps.newHashMap();
static {
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
//Collections.unmodifiable** 处理过的对象不能再修改
map = Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
//编译通过但是执行会报错
Integer put = map.put(1, 3);
log.info("{}", map.get(1));
}
}
执行报错如下:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at com.zjq.concurrency.immutable.ImmutableExample2.main(ImmutableExample2.java:31)
Collections.unmodifiable**原理:
1.重新赋值了一个不可变的UnmodifiableMap<>(m)对象
2.这个UnmodifiableMap 中,所有操作map的方法,都会抛出异常
Collections 的unmodifiable**对象:
guava Immutable**
@ThreadSafe
public class ImmutableExample3 {
private final static ImmutableList<Integer> list = ImmutableList.of(1, 2, 3);
private final static ImmutableSet set = ImmutableSet.copyOf(list);
private final static ImmutableMap<Integer, Integer> map = ImmutableMap.of(1, 2, 3, 4);
private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap.<Integer, Integer>builder()
.put(1, 2).put(3, 4).put(5, 6).build();
public static void main(String[] args) {
//不可变对象进行变更操作都会抛出异常
//运行时,会抛出异常
list.add(4);
//运行时,会抛出异常
set.add(66);
//运行时,会抛出异常
map.put(6,8);
//运行时,会抛出异常
map2.put(9,8);
//获取正常
System.out.println(map2.get(3));
}
}
guava的 Immutable 原理与Collections.unmodifiable类似不再赘述。
本文内容到此结束了,
如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
如有错误❌疑问💬欢迎各位大佬指出。
保持热爱,奔赴下一场山海。🏃🏃🏃
转载自:https://juejin.cn/post/7128193674772480007