gpt4 book ai didi

java - 为什么 Intellij Idea 建议在使用循环将数组转换为 Set 时创建中间列表?

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:06 26 4
gpt4 key购买 nike

假设我有以下代码:

public Set<String> csvToSet(String src) {
String[] splitted = src.split(",");
Set<String> result = new HashSet<>(splitted.length);
for (String s : splitted) {
result.add(s);
}
return result;
}

所以我需要将数组转换为 Set。Intellij Idea 建议用 Collection.addAll 一行替换我的 for-each 循环,这样我得到:

...
Set<String> result = new HashSet<>(splitted.length);
result.addAll(Arrays.asList(splitted));
return result;

完整的检测信息为:

This inspection warns when calling some method in a loop (e.g. collection.add(x)) could be replaced when calling a bulk method (e.g. collection.addAll(listOfX). If checkbox "Use Arrays.asList() to wrap arrays" is checked, the inspection will warn even if the original code iterates over an array while bulk method requires a Collection. In this case the quick-fix action will automatically wrap an array with Arrays.asList() call.

从检查描述来看,它听起来像预期的那样工作。

如果我们引用关于将数组转换为集合 (How to convert an Array to a Set in Java) 的问题的最佳答案,则建议使用相同的衬里:

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));

尽管从数组创建 ArrayList 的时间复杂度为 O(1),但我不喜欢创建额外的 List 对象的想法。

通常我相信 Intellij 检查并假设它不会提供任何效率较低的东西。但今天我很好奇为什么两个:顶级 SO 答案和 Intellij Idea(使用默认设置)建议使用相同的单行创建无用的中间 List 对象,同时还有一个 Collections.addAll(destCollection, yourArray) 从 JDK 6 开始。

我看到的唯一原因是(检查和答案)都太旧了。如果是这样,这就是改进 intellij idea 并为提出 Collections.addAll() :)

的答案提供更多选票的原因

最佳答案

关于为什么 Intellij 不建议用 Arrays.asList 替换

的提示
Set<String> result = new HashSet<>(splitted.length);
result.addAll(Arrays.asList(splitted));
return result;

source code for HashSet(Collection) 中:

public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}

请注意,集合的容量不是 c 的大小。

因此,更改在语义上不会等同。


不要担心创建 List。它真的便宜。它不是免费的;但您必须在真正对性能至关重要的循环中使用它才能注意到。

关于java - 为什么 Intellij Idea 建议在使用循环将数组转换为 Set 时创建中间列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48207118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com