Suppose I had the following code:
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;
}
so I need to transform an array into Set.
And Intellij Idea suggests to replace my for-each loop with Collection.addAll
one-liner so I get:
...
Set<String> result = new HashSet<>(splitted.length);
result.addAll(Arrays.asList(splitted));
return result;
The complete inspection message is:
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.
From inspection description it sounds like it works as expected.
If we refer to a top answer of a question about converting an array into Set (How to convert an Array to a Set in Java) the same one liner is suggested:
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
Even though creating an ArrayList from array is O(1), I do not like the idea of creating an additional List object.
Usually I trust Intellij inspections and assume it does not offer anything less efficient.
But today I am curious why both: top SO answer and Intellij Idea (with default settings) recommend using same one-liner with creating useless intermediate List object while there is also a Collections.addAll(destCollection, yourArray)
since JDK 6.
The only reason I see for it is that both (inspection and answers) are too old. If so, here is the reason to improve intellij idea and give more votes to an answer proposing Collections.addAll()
:)