[英]Is there a way to refactor a Set initialization to use Set.of() using IntelliJ?
Is there a way to refactor this in IntelliJ (or even with Eclipse), to transform the first script to the second one :有没有办法在 IntelliJ(甚至使用 Eclipse)中重构它,将第一个脚本转换为第二个脚本:
Set initialization before Java 9 :在 Java 9 之前设置初始化:
Set<String> values = new HashSet<>();
values.add("a");
values.add("b");
Set initialization starting from Java 9 (creates an immutable set) :从 Java 9 开始设置初始化(创建一个不可变的集合):
Set<String> values = Set.of("a", "b");
The refactoring option may not be available in all the cases (the source set should be unmodifiable).重构选项可能并非在所有情况下都可用(源集应该是不可修改的)。
However IntelliJ has inspections that may be more suitable to detect such a case.然而,IntelliJ 的检查可能更适合检测这种情况。
See under Java > Java language level migration aids > Java 9 : Immutable collection creation can be replaced with collection factory call :请参阅Java > Java 语言级别迁移辅助工具 > Java 9 :不可变集合创建可以替换为集合工厂调用:
This inspection helps to convert unmodifiable collections created before Java 9 to new collection factory methods like
List.of
orSet.of
.此检查有助于将 Java 9 之前创建的不可修改集合转换为新的集合工厂方法,如
List.of
或Set.of
。 Also since Java 10 the conversion toList.copyOf
, etc. could be suggested.此外,从 Java 10
List.copyOf
,可以建议转换为List.copyOf
等。Note that Java 9 collection factory methods do not accept null values.
请注意,Java 9 集合工厂方法不接受空值。 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.
此检查仅从 Java 9 开始可用。
New in 2017.22017.2 新增
This inspection can be tested with this code :可以使用以下代码测试此检查:
Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.