Java 返回一个空列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28406921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java return an empty list
提问by testndtv
I have my Java method as below;
我的 Java 方法如下;
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
}
}
Now the method returns List for valid matches of lang.
现在该方法返回有效匹配的 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 ?
但如果情况并非如此,我想返回一个空列表。我的问题是如何更新代码以及返回空列表以便代码不会失败的最佳方法是什么?
回答by Mike Nakis
This should do it:
这应该这样做:
} else {
return Collections.emptyList();
}
Notes:
笔记:
- As of java 9, besides
Collections.emptyList()
there is alsoList.of()
. - 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.
- As others have pointed out, this list returned by
Collections.emptyList()
andList.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. - 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 9 开始,除了
Collections.emptyList()
还有List.of()
. - 这种构造是最有效的,因为它重用了空列表的现有实例,因此每次请求空列表时,都不会创建新列表。(任何泛型类型。)然而,Java 中的对象分配非常便宜,所以这不应该是一个真正的问题。
- 正如其他人指出的那样,这个列表返回
Collections.emptyList()
并且List.of()
是秘密不可变的。“秘密地”我的意思是它公开了变异方法,但是如果你错误地调用了这些方法中的任何一个,你就会得到一个异常。在其他比 Java 更好的语言中(例如,在 Scala 中)存在不可变/不可修改的集合,但 Java 没有“开箱即用”的东西。因此,如果您在 2020 年坚持使用 Java,那么您将接受并非所有集合都可以写入的可能性,尽管它们看起来都可以写入。 - 通常,函数旨在返回不可变实体,因此如果您调用一个返回集合的函数,然后修改该集合,那么您就做错了。如果你真的需要这样的结构,你应该写一个函数来填充你作为参数传递给它的可变列表,所以很明显,作为可变列表的所有者,你可以自由地进一步修改列表函数返回后。
回答by Kiki
Try it like this:
像这样尝试:
public List<Lookup> findAll(String lang) {
List<Lookup> result = new ArrayList<Lookup>();
Query query = entityManager.createNamedQuery("Lookup.findAll");
if (isValidLang(lang)) {
query.setParameter("lang", lang);
result = query.getResultList();
}
return result;
}
回答by atish shimpi
Collections.emptyList()
returns an immutable list, i.e., a list to which you cannot add elementsif you want to perform any operation on your list, then create new instance of list and return it.
Collections.emptyList()
返回一个不可变的列表,即,如果您想对列表执行任何操作,则无法向其中添加元素的列表,然后创建列表的新实例并返回它。
if (isValidLang(lang)) {
query.setParameter("lang", lang);
return query.getResultList();
} else {
return new ArrayList<Lookup>(); // return array list instance.
}
回答by Razib
Using ternary operator (boolean_expression ? statement1 : statemetn2 )
in java
we can check every return type whether it is null
. If we do this once then every calling method using the code will be benefited because they do not have to check against null
. Your code can be rewritten like this -
使用ternary operator (boolean_expression ? statement1 : statemetn2 )
injava
我们可以检查每个返回类型是否为null
。如果我们这样做一次,那么使用代码的每个调用方法都会受益,因为它们不必检查null
. 您的代码可以像这样重写 -
public List<Lookup> findAll(String lang) {
Query query = entityManager.createNamedQuery("Lookup.findAll");
ArrayList lookupList = null;
if (isValidLang(lang)) {
query.setParameter("lang", lang);
lookupList = <ArrayList> query.getResultList();
}
return (null != lookupList ? lookupList : Collections.EMPTY_LIST);
}