java - 有没有办法使用 IntelliJ 重构 Set 初始化以使用 Set.of() ?

标签 java intellij-idea java-9

有没有办法在 IntelliJ(甚至使用 Eclipse)中重构它,将第一个脚本转换为第二个脚本:

在 Java 9 之前设置初始化:

Set<String> values = new HashSet<>();
values.add("a");
values.add("b");

从 Java 9 开始设置初始化(创建不可变集):

Set<String> values = Set.of("a", "b");

最佳答案

重构选项可能并非在所有情况下都可用(源集应该是不可修改的)。

但是 IntelliJ 有 inspections这可能更适合检测这种情况。

请参见Java > Java 语言级别迁移辅助工具> Java 9 :不可变集合创建可以替换为集合工厂调用:

This inspection helps to convert unmodifiable collections created before Java 9 to new collection factory methods like List.of or Set.of. Also since Java 10 the conversion to List.copyOf, etc. could be suggested.

Note that Java 9 collection factory methods do not accept null values. Also set elements and map keys are required to be different. It's not always possible to statically check whether original elements are different and not null. Using the checkbox you may enforce the inspection to warn only if original elements are compile-time constants, so the conversion is guaranteed to be correct.

This inspection is available since Java 9 only.
New in 2017.2

可以使用以下代码测试此检查:

Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

关于java - 有没有办法使用 IntelliJ 重构 Set 初始化以使用 Set.of() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160647/

相关文章:

Java JPanel 清除

java - 列出应用程序启动期间解析的模块

java - 错误 :java: invalid flag: -release

java - Guice - 使用静态辅助方法将依赖项注入(inject)类

java - 通用接口(interface)

java - Tomcat下war文件中的index.jsp

intellij-idea - 为什么 IntelliJ 为简单的 hello world 程序从 JDK 1.6 导入额外的库?

android - org.apache.commons.collections.BeanMap : can't find referenced class java. beans.Introspector

java - CountedCompleter类中 "private static final VarHandle PENDING"的作用是什么

java - 对 double 数据类型的大量操作结果为零