Java中的不可变对象
一.需要的条件
不可变对象需要满足的条件
- 对象创建之后其状态就不可改变
- 对象所有域都是final类型
- 对象是正确创建的(在对象创建期间,this引用没有逸出)
二.final关键字修饰
final关键字:类、方法、变量
- 修饰类:不能被继承
- 修饰方法:1、锁定方法不被继承类修改;2、效率
- 修饰变量:基本数据类型变量、引用类型变量
三.其他定义不可变对象的方式
- Java中的Collections.unmodifiableXXX
- 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);
}
}