Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Intellij: Warning: 'List<String>' may not contain objects of type 'List<String>' (Suspicious collections method calls)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading