java 不可变对象 final Collections guava 简单样例

时间:2023-11-22 13:34:38

本地环境

  • jdk1.8

连接

说明

java的final关键字大家都了解,但是final修饰的如果是引用类型,那么不可修改的其实只是重新赋值,是可以修改引用对象中的属性值的。

那如何来构建一个不可修改的list、map、set等这些对象呢,可以通过jdk自带的Collections,也可以通过google的guava来进行构建。

代码样例

import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lombok.extern.slf4j.Slf4j; /**
* <dependency>
* <groupId>org.projectlombok</groupId>
* <artifactId>lombok</artifactId>
* <version>1.18.8</version>
* </dependency>
*
* <dependency>
* <groupId>com.google.guava</groupId>
* <artifactId>guava</artifactId>
* <version>23.0</version>
* </dependency>
*/
@Slf4j
public final class UnModify { // 初始化一个 final 修饰的list
private static final List finalList = new ArrayList();
// 初始化一个由 Collections 构建的list
private static List collectionsList = new ArrayList();
// 初始化一个由 guava 构建的list
private static final List immutableList = ImmutableList.of(1, 2, 3); static {
finalList.add(1);
finalList.add(2);
finalList.add(3); collectionsList.add(1);
collectionsList.add(2);
collectionsList.add(3);
collectionsList = Collections.unmodifiableList(collectionsList);
} public static void main(String[] args){ log.info(finalList.toString());
finalList.set(0, 4);
log.info(finalList.toString()); /*
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1311)
*/
log.info(collectionsList.toString());
collectionsList.set(0, 5);
log.info(collectionsList.toString()); /*
Exception in thread "main" java.lang.UnsupportedOperationException
at com.google.common.collect.ImmutableList.set(ImmutableList.java:512)
*/
log.info(immutableList.toString());
immutableList.set(0, 6);
log.info(immutableList.toString()); }
}