StringUtils.defaultString 是集合的委婉说法吗?
是否有与 StringUtils.defaultString 类似的集合方法,这样您就可以避免检查空值,因为在大多数情况下,所需的效果与空列表相同?
替换
if (list != null) {
for (String item: list) {
// ...
}
}
之类的东西
for (String item: ListUtils.defaultList(list)) {
// ...
}
例如,用诸如“使用三元运算符”
List<String> safelista = (List<String>) (list != null ? list : Collections.emptyList());
List<String> safelistb = (list != null ? list : Collections.EMPTY_LIST);
是非常难看的,并且会导致未经检查的转换错误:将其内联甚至更难看。
Is there an analogous method to StringUtils.defaultString for collections, so you can avoid checking for null value, since in most cases, the desired effect is the same as if it were an empty list?
e.g. to replace
if (list != null) {
for (String item: list) {
// ...
}
}
with something like
for (String item: ListUtils.defaultList(list)) {
// ...
}
Using the ternary operator is pretty ugly and cause unchecked casting errors:
List<String> safelista = (List<String>) (list != null ? list : Collections.emptyList());
List<String> safelistb = (list != null ? list : Collections.EMPTY_LIST);
Putting it inline is even uglier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否可以控制返回相关列表的方法?如果是这样,我会更改它,使其永远不会返回 null,而只是返回一个空列表。这也是更正常的惯例。
Do you have control over the method which returns the list in question? If so, I'd change it so that it never returns null, but just an empty list for the case that. That's also more the normal convention.
您必须定义一个使用
if()
的辅助函数,而不是使用三级运算符:Instead of using the tertiary operator, you must define a helper function which uses
if()
: