【问题标题】:I am trying to return an empty list我正在尝试返回一个空列表
【发布时间】:2019-08-03 09:23:30
【问题描述】:

我是列表新手,但我试图通过一种方法返回一个空列表,以便可以在其他地方使用该列表。但我不知道该怎么做。

public List<Something> login (String user, String key){
    if (success) {
        System.out.println("Welcome");
        return  (THIS IS WHERE I WANT TO RETURN AN EMPTY LIST);
    } 

    System.out.println("Incorrect Information");
        return null;
}

【问题讨论】:

  • 你能不能只在需要的地方创建List,而不是在这里返回一个空的?

标签: java list oop if-statement arraylist


【解决方案1】:

如果你打算在其他地方使用它,你可以返回List 接口的任何实现。最常用的:

new ArrayList<>();

还有一些方法可以返回一个不可变的空列表(意味着你不能修改它):

return Collections.emptyList();
return List.of();  // from java9

查看它们之间的区别List.of() or Collections.emptyList()

还可以查看有关List implementations 的更多信息

【讨论】:

  • 值得注意的是 emptyList() 和 of() 返回两种不同类型的 List(它们在实现上有点不同)。
【解决方案2】:

怎么样:

return new ArrayList<>();

【讨论】:

  • 你能解释一下吗
  • 没什么好解释的,真的。我们正在实例化一个空列表并返回它。
【解决方案3】:

java.util.List 是一个接口,因此您不能实例化一个。

您应该实例化其中一个实现类并返回该对象。

点赞return new ArrayList&lt;&gt;();

【讨论】:

  • 是的,但看起来他试图这样做 return new List(); 并且 IDE 不允许他这样做;造成一些混乱:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
相关资源
最近更新 更多