Java不可变对象

不可变对象定义,作用,使用方式详解。

  • 不可变对象需要满足的条件:
    • 对象创建以后其状态就不能修改
    • 对象所有域都是final类型
    • 对象时正确创建的(在对象创建期间,this引用没有逸出)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//final关键字:类,方法,变量
// 修饰类:不能被继承
// 修饰方法:1.锁定方法不能被继承类修改(默认为private);2.效率
// 修饰变量:基本数据类型变量,引用类型变量
@Slf4j
@NotThreadSafe
public class ImmutableFinal {
private final static Integer a = 1;
private final static String b = "2";
//guava
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 = 2;
//b = "3";
//map = Maps.newHashMap();
//map引用不能修改,但是内部的值还是可以进行修改~
map.put(1, 3);
log.info("{}",map.get(1));
}

//final参数不能修改
private void test(final int a){
// a = 1
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
////利用基本的类库进行不可变Map对象的创建(内部参数也不可以改变)
@Slf4j
@ThreadSafe
public class ImmutableMap {
private static Map<Integer, Integer> map = Maps.newHashMap();

static{
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
//java
map = Collections.unmodifiableMap(map);
}

public static void main(String[] args) {
//会报错哈~UnsupportedOperationException
map.put(1, 3);
log.info("{}", map.get(1));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//利用Guava的类库进行不可变Map对象的创建(内部参数也不可以改变)
@ThreadSafe
public class ImmutableGuava {
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) {
System.out.println(map2.get(3));
}
}