rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

Replace Arrays.asList

Open kthoms opened this issue 10 months ago • 2 comments

What problem are you trying to solve?

IJ IDEA issues warnings for usages of Arrays#asList() with a single argument.

What precondition(s) should be checked before applying this recipe?

Java language level should be at least 9

Describe the situation before applying the recipe

import java.util.Arrays;

class A {
  void foo() {
    Arrays.asList("foo", "bar");
  }
}

Describe the situation after applying the recipe

import java.util.List;

class A {
  void foo() {
    List.of("foo", "bar");
  }
}

Any additional context

List.of() is only valid for up to 10 arguments.

Are you interested in contributing this recipe to OpenRewrite?

yes

kthoms avatar Feb 16 '25 07:02 kthoms

  • https://github.com/openrewrite/rewrite-static-analysis/pull/466

greg-at-moderne avatar Mar 20 '25 14:03 greg-at-moderne

As discussed on the PR we're not sure there's a good safe way to limit this to just the cases where it is safe to do so, as Arrays.asList() returns a new ArrayList<>() (although it makes no guarantees of doing so), whereas List.of() return an unmodifiable collection. Until we find a good way to limit the changes it's best not do any potential harm.

timtebeek avatar Jun 02 '25 09:06 timtebeek