list != null?
|
1
list != null
list.size != 0 |
|
allanzhuoMay 29, 2019
2
Optional
|
|
FringJXMay 29, 2019
3
java 有集合工具类可以判断
|
|
4
CollectionUtils.isNotEmpty
|
|
zhangqilinMay 29, 2019
5
python?
if xxx: # 不为空 |
|
obliviousMay 29, 2019 via iPhone
6
if some_list:
Do something else: Do something else |
|
demoMay 29, 2019
9
list || []
|
|
10
Effective Java, Item54: Return empty collections or arrays, not nulls
|
|
securityCodingMay 29, 2019
11
楼上+1
|
|
yalinMay 29, 2019
12
!CollectionUtils.isEmpty(list)
|
|
chendyMay 29, 2019
13
能用 `Collecitons.emplyList()` 的地方就用,使用方一个 `.isEmpty()` 就行了
|
|
14
list = Optional.ofNull(list).orElse(Collecitons.emplyList())
|
|
jzmwsMay 29, 2019
15
Optional 大法好
|
|
mapperMay 29, 2019
16
目前用的最多的是 CollectionUtils.isNotEmpty(list), 该方法就等同于 list != null && list.size() > 0
|
|
SuperMildMay 29, 2019
17
老代码没办法,新代码上 Optional
|
|
chengxyMay 29, 2019
18
!!list.length
|
|
jorneyrMay 29, 2019
19
我们是强制规定接口返回数据的时候,没有数据时必须返回空集合,不能返回 null,这样就不需要处理集合的时候进行 null 判断了,直接遍历。
MyBatis 的 Mapper 返回集合类型也是没有查询到数据时返回空集合。 |
|
wysnylcMay 29, 2019
20
CollectionUtils
|
|
shakarakaMay 29, 2019
21
list.length <= 0 ? false : true
|
|
TakamineMay 29, 2019
24
if list :
empty(list) list || [] CollectionUtils 等等。 |
|
dabaituMay 29, 2019 via Android
25
kotlin
list.let |
|
Em5O7B1JGfjQnBryMay 29, 2019 via Android
26
Rust、Haskell:没有 null,不能每次都判断 null,真羡慕你们这些成功的语言。
|
|
fengjianxinghunMay 29, 2019
27
Rust 没有 null,不需要判断
|
|
siteshenMay 29, 2019
28
这个问题有歧义太大,导致答案五花八门,建议楼主补充一下问题的细节:
1. 用什么编程语言? 2. 谁要避免空 list ?是 producer 避免接收空 list 还是 consumer 避免产生空 list ? 3. 什么是“空”?元素个数为零,还是空指针,还是两者都是“空”? |
|
chinjanryMay 29, 2019
29
List<Xxx> outputList = MoreObjects.firstNonNull(inputList, Lists.newArrayList());
|
|
wr410May 29, 2019
30
为什么你们都可以随便使用第三方包?
我们通常只给用 jdk 和 org.apache 的包。 |
|
8a9a09dw12May 29, 2019
32
assert 了解一下
|
|
Jrue0011May 29, 2019 via iPhone
33
@wr410 也没别的包吧,CollectionUtils 是 apache commons 的,Optional 和 Collections 是 jdk 的,只有 MoreObjects 好像是 guava 的…
|
|
linvauxMay 29, 2019 via Android
35
不用 list 不就好了,咳咳,认真点,用 guava 的 optional
|
|
syasukerMay 29, 2019
36
Utils.isListEmpty
|
|
lihongjie0209May 29, 2019
37
集合就不应该是 null, 只应该是 empty
|
|
wombatMay 29, 2019
38
4 楼
|
|
AresxueMay 30, 2019
39
申明的时候赋值一个空列表, Collections.EMPTY_LIST 这个就是专用的空列表不会占用内存。
|
|
troywinterMay 30, 2019
40
尽信书不如无书,虽然 effective java 建议返回 emptyList(),但是还是要分清场景,如果你之后不需要对这个 list 继续 modify,那么使用 emptyList 没有问题,但如果你后续的业务逻辑需要进一步对这个 list 做 modify,那么就会出现 exception,因为 emptyList 返回了 List<T>类型,实际是 immutable 的,就会出现 exception。所以遇到这种问题还是要多看源码结合自己的实际需求做取舍,no silver bullet.
|