Home > database >  Intellij: Warning: 'List<String>' may not contain objects of type 'List<Stri
Intellij: Warning: 'List<String>' may not contain objects of type 'List<Stri

Time:08-10

Below is a code snippet where intellij is throwing a Suspicious collections method calls warning, but I don't understand why. The only thing I can think of is that maybe intellij thinks one of the lists could be null, but that also throws the same error.

Is this an Intellij bug, or is there really some corner case that I'm not thinking of?

public class Foo {
    public static void main(String[] args) {
        List<String> foo = Arrays.asList("a", "b", "c");
        List<String> bar = new ArrayList<>(foo);
        bar.remove(foo); // Warning: 'List<String>' may not contain objects of type 'List<String>'
    }
}

public class Foo {
    public static void main(String[] args) {
        List<String> foo = Arrays.asList("a", "b", "c");
        List<String> bar = new ArrayList<>(foo);
        if (foo != null && bar !=null) {
            bar.remove(foo); // Warning: 'List<String>' may not contain objects of type 'List<String>'
        }
    }
}

Intellij version 2022.1.4 Ultimate

CodePudding user response:

List<String> foo = Arrays.asList("a", "b", "c");
List<String> bar = new ArrayList<>(foo);

// bar.remove(foo); This is the same thing as:
bar.remove(Arrays.asList("a", "b", "c")); // still makes no sense.

// What would make sense:
bar.remove("a"); // remove the element "a"
bar.removeAll(foo); // remove all the elements in foo

In short, in a List<String>, you're usually going to be calling remove(String) or removeAll(Collection<String>), not remove(List<String>), which won't really do what you want.

CodePudding user response:

List<String> bar = new ArrayList<>(foo);

constructs a list containing the elements of foo, not foo itself,

  • Related