Why does Idea suggest to replace Arrays.asList(o) with Collections.singletonList(o)?
Answered
Difference in behaviors of List objects returned by Arrays.asList(o) vs Collections.singletonList(o) is very subtle, but it exists, it lies in the implementation of #set() method, which will produce UnsupportedOperationException in case of Collections.singletonList(o).
Still Idea issues a warning saying "Call to 'asList' with only one argument" and suggests replacing it with Collections#singletonList without notifying of possible changes in behavior.
Should this be considered a safe refactor?
Please sign in to leave a comment.
This concern has been already raised by one of the users:
The inspection is called "Call to 'Arrays.asList()' with too few arguments", and will change calls to Arrays.asList with 1 argument to Collections.singletonList. The problem is that these two methods are not equivalent, since the latter yields an immutable list, which in turn will lead to an exception if one tries to sort it or add elements to it.
The response was:
It's indeed possible to invoke 'set' method on lists returned from Arrays.asList (and also invoke 'Collections.sort'), but 'add' and 'remove' method will throw UnsupportedOperationException for this list as well. So the quickfix indeed may break the code in very rare cases. Probably it would be enough to mention it in the quickfix description.
As far as I can see, it was not mentioned in the quick fix description, so a request for this is welcome at https://youtrack.jetbrains.com/issues/IDEA.