Java 返回一个空列表 [英] Java return an empty list

查看:60
本文介绍了Java 返回一个空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Java 方法如下;

I have my Java method as below;

public List<Lookup> findAll(String lang) {
    Query query = entityManager.createNamedQuery("Lookup.findAll");
    if (isValidLang(lang)) {
        query.setParameter("lang", lang);
        return query.getResultList();
    } else {
        //return empty list
    }
}

现在该方法返回有效匹配的 lang 列表.

Now the method returns List for valid matches of lang.

但如果不是这样,我想返回一个空列表.我的问题是如何更新代码 &返回空列表以便代码不会失败的最佳方法是什么?

But if that is not the case, I want to return an empty list. My question is how do I update the code & what is the best way to return an empty list so that the code does not fail ?

推荐答案

应该这样做:

} else { 
    return Collections.emptyList();
}

注意事项:

  1. 从 java 9 开始,除了 Collections.emptyList() 之外,还有 List.of().
  2. 这个结构是最有效的,因为它重用了一个空列表的现有实例,所以每次你请求一个空列表时,不会创建新的列表.(任何泛型类型.)但是,Java 中的对象分配非常便宜,因此这不应该成为真正的问题.
  3. 正如其他人指出的那样,由 Collections.emptyList()List.of() 返回的这个列表是秘密不可变的.秘密地"我的意思是它公开了变异方法,但是如果你错误地调用了这些方法中的任何一个,你就会得到一个异常.在其他比 Java 更好的语言中(例如,在 Scala 中)存在不可变/不可修改的集合,但 Java 没有开箱即用"的东西.因此,如果您在 2020 年坚持使用 Java,那么您将接受并非所有集合都可以写入的可能性,尽管它们看起来都可以写入.
  4. 一般来说,函数旨在返回不可变的实体,因此如果您调用一个返回集合的函数,然后修改该集合,那么您就做错了.如果你真的需要这样的结构,你应该写一个函数来填充你作为参数传递给它的可变列表,所以很明显,作为可变列表的所有者,你可以自由地进一步修改列表在函数返回之后.
  1. As of java 9, besides Collections.emptyList() there is also List.of().
  2. This construct is the most efficient one, because it reuses an existing instance of an empty list, so each time you ask for an empty list, no new list gets created. (Of any generic type.) However, object allocation in Java is very inexpensive, so this should not really be a concern.
  3. As others have pointed out, this list returned by Collections.emptyList() and List.of() is secretly immutable. By "secretly" I mean that it exposes mutation methods, but if you make the mistake of invoking any of those methods, you will get an exception. In other, better languages than Java, (for example, in Scala,) there exist immutable / unmodifiable collections, but Java does not have such a thing "out of the box". So, if you are sticking with Java in 2020, you are accepting the possibility that not all of your collections can be written to, despite the fact that they all look as if they can be written to.
  4. In general, functions are meant to return immutable entities, so if you are invoking a function which returns a collection and then you modify this collection, you are doing it wrong. If you really need such a construct, you should instead write a function which populates a mutable list that you pass to it as a parameter, so it is evident that you, as the owner of the mutable list, are free to further modify the list after the function returns.

这篇关于Java 返回一个空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆