你们是怎么避免 list 为空

2019-05-29 10:23:56 +08:00
 zxcjqyy
list != null?
6582 次点击
所在节点    程序员
40 条回复
NoKey
2019-05-29 10:30:17 +08:00
list != null
list.size != 0
allanzhuo
2019-05-29 10:50:31 +08:00
Optional
hfl1995
2019-05-29 11:13:13 +08:00
java 有集合工具类可以判断
l8g
2019-05-29 11:15:19 +08:00
CollectionUtils.isNotEmpty
zhangqilin
2019-05-29 11:18:12 +08:00
python?
if xxx:
# 不为空
oblivious
2019-05-29 11:18:20 +08:00
if some_list:
Do something
else:
Do something else
DrJoseph
2019-05-29 11:32:58 +08:00
@l8g +1
reindeer
2019-05-29 11:36:15 +08:00
@l8g +2
demo
2019-05-29 11:41:24 +08:00
list || []
aijam
2019-05-29 11:50:52 +08:00
Effective Java, Item54: Return empty collections or arrays, not nulls
securityCoding
2019-05-29 11:53:17 +08:00
楼上+1
yalin
2019-05-29 11:55:36 +08:00
!CollectionUtils.isEmpty(list)
chendy
2019-05-29 12:08:31 +08:00
能用 `Collecitons.emplyList()` 的地方就用,使用方一个 `.isEmpty()` 就行了
zrc
2019-05-29 12:43:06 +08:00
list = Optional.ofNull(list).orElse(Collecitons.emplyList())
jzmws
2019-05-29 14:23:45 +08:00
Optional 大法好
mapper
2019-05-29 14:24:47 +08:00
目前用的最多的是 CollectionUtils.isNotEmpty(list), 该方法就等同于 list != null && list.size() > 0
SuperMild
2019-05-29 14:29:38 +08:00
老代码没办法,新代码上 Optional
chengxy
2019-05-29 15:42:47 +08:00
!!list.length
jorneyr
2019-05-29 15:47:04 +08:00
我们是强制规定接口返回数据的时候,没有数据时必须返回空集合,不能返回 null,这样就不需要处理集合的时候进行 null 判断了,直接遍历。

MyBatis 的 Mapper 返回集合类型也是没有查询到数据时返回空集合。
wysnylc
2019-05-29 15:50:12 +08:00
CollectionUtils

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/568656

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX