一、不可变对象需要满足的条件
1、对象创建以后其状态就不能修改
2、对象所有域都是final类型
3、对象是正确创建的(在对象创建期间,this 引用没有逸出)
二、final关键字、修饰类方法变量
1、修饰类: 不能被继承
2、修饰方法:
- 锁定方法不被继承类修改
- 效率
3、修饰变量: 基本数据类型变量、引用类型变量
package com.current.flame.immutable;
import com.current.flame.annoations.NotThreadSafe;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* @author haoxiansheng
*/
@Slf4j
@NotThreadSafe
public class ImmutableExample {
public static void main(String[] args) {
//a = 2;
//b ="3";
//map = Maps.newHashMap(); // 不允许指向新的引用
log.info("map=>{}", map);
map.put(1,4);
log.info("map=>{}", map);
}
private final static Integer a = 1;
private final static String b = "a";
private final static Map<Integer, Integer> map = Maps.newHashMap(); // 线程不安全
static {
map.put(1,2);
map.put(2,3);
map.put(3,4);
}
private void testFinal(final int b) {
//a = 1;
}
}
4、Collection.unmodifibleXXX:Collection、List、Set、Map…
package com.current.flame.immutable;
import com.current.flame.annoations.ThreadSafe;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import java.util.Collections;
import java.util.Map;
/**
* @author haoxiansheng
*/
@Slf4j
@ThreadSafe
public class ImmutableExample2 {
public static void main(String[] args) {
log.info("map=>{}", map);
map.put(1,4);
log.info("map=>{}", map);
}
private static Map<Integer, Integer> map = Maps.newHashMap(); // 线程不安全
static {
map.put(1,2);
map.put(2,3);
map.put(3,4);
map = Collections.unmodifiableMap(map);
}
}
5、Guava:ImmutableXXX:Collection、List、Set、Map…
package com.current.flame.immutable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
/**
* @author haoxiansheng
*/
@Slf4j
public class ImmutableExample3 {
private final static ImmutableList list = ImmutableList.of(1,2,2,3,4);
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)
.build();
public static void main(String[] args) {
//list.add(4); //运行出错
//set.add(3); //运行出错
//map.put(5,6); //运行出错
//map2.put(7,8); //运行出错
}
}