不可变对象需要满足的条件:
- 对象创建以后其状态就不能修改
- 对象所有域都是final类型
- 对象是正确创建的(在对象创建期间,this引用没有逸出)
final关键字:类、方法、变量
- 修饰类:不能被继承,final修饰类的所有方法都被隐式修饰为fianl方法
- 修饰方法:1、锁定方法不被继承类修改;2、效率
- 修饰变量:基本数据类型变量(初始化后不能再修改),引用类型变量(初始化后不能再指向另外一个对象,对象里的值可以改变)
其他不可变对象:
Collections.unmodifiableXXX:Collection、List、Set、Map…
使用方法:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
List<Integer> unmodifiableList = Collections.unmodifiableList(list);
}
具体实现就是把原来的List数据结构复制重新返回个不可变对象:
Guava:ImmutableXXX:Collection、List、Set、Map…
常见用法:
ImmutableList<Integer> immutableList1 = ImmutableList.<Integer>builder().add(1,2,3,4).build();
ImmutableList<Integer> immutableList2 = ImmutableList.of(1,2,3,4);
ImmutableSet<Integer> immutableSet = ImmutableSet.copyOf(immutableList2);
ImmutableMap<Integer, Integer> immutableMap1 = ImmutableMap.of(1, 1, 2, 2, 3, 3, 4, 4);
ImmutableMap<Integer, Integer> immutableMap2 = ImmutableMap.<Integer,Integer>builder().put(1, 1).put(2, 2).build();
在多线程下多使用不可变对象,可以减少线程安全问题的发生。