首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Intellij:警告:'List<String>‘可能不包含'List<String>’类型的对象(可疑的集合方法调用)

Intellij:警告:'List<String>‘可能不包含'List<String>’类型的对象(可疑的集合方法调用)
EN

Stack Overflow用户
提问于 2022-08-09 19:39:52
回答 2查看 214关注 0票数 0

下面是intellij抛出Suspicious collections method calls警告的代码片段,但我不明白为什么。我唯一能想到的是,也许intellij认为其中一个列表可能为空,但这也会引发相同的错误。

这是一个Intellij错误,还是真的有某个角落的情况,我没有想到?

代码语言:javascript
运行
复制
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>'
    }
}
代码语言:javascript
运行
复制
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版本2022.1.4终极版

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-09 19:45:14

代码语言:javascript
运行
复制
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

简而言之,在List<String>中,您通常会调用remove(String)removeAll(Collection<String>),而不是remove(List<String>),后者不会真正做您想做的事情。

票数 6
EN

Stack Overflow用户

发布于 2022-08-09 20:07:29

代码语言:javascript
运行
复制
List<String> bar = new ArrayList<>(foo);

构造包含foo元素的列表,而不是foo本身,

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73297257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档