英文:
Providing an Empty List to an Optional?
问题
假设我有以下布局:
```java
public void caller(@NonNull List<Integer> param){
// param可以是空的,但不能为null,它不可为空
if(!param.isEmpty()) function(Optional.of(param));
// 如果param是空的,那就不要调用"function"
}
public void function(Optional<List<Integer>> someParam){
someParam.ifPresent(...);
}
问题是:基于空列表创建Optional
是否是正确的用法?我感到困惑的是,我们是否应该提供一个Optional
,无论caller
中的param
是否为空,因为它不为null,但我想知道这是否是正确的用法?
<details>
<summary>英文:</summary>
Suppose I have this layout:
public void caller(@NonNull List<Integer> param){
// param COULD BE EMPTY, but it CANNOT be NULL, its not nullable
if(!param.isEmpty()) function(Optional.of(param));
// If param is empty then just dont call "function"
}
public void function(Optional<List<Integer>> someParam){
someParam.ifPresent(...);
}
Here is the question: Is not creating an `Optional` based on an empty list correct usage? The confusion I am having is whether we should be providing an Optional regardless if `param` in `caller` is empty or not because it is not null, but I am wondering if this is the right usage?
</details>
# 答案1
**得分**: 3
1. `someParam.ifPresent(...);` `ifPresent` 方法的主体总是会被调用,因为总是会有一个元素,即使它是一个空列表(你正在检查非空性 `@NonNull List<Integer> param`)。
2. 你正在使用 `Optional.of` 而不是 `Optional.ofNullable`,因此始终会有一个非空元素。
3. 将列表包装在 `Optional` 中没有太多意义,为什么不传递一个空列表并且不处理任何元素呢?
4. `if(!param.isEmpty())` 是多余的,因为你知道列表中有元素,就像第3点所述,为什么不直接传递列表进行处理呢?
**简而言之**:你将空列表与 `null` 混淆了,在任何集合中包装 `Optional` 都没有太多意义。
<details>
<summary>英文:</summary>
1. `someParam.ifPresent(...);` the body of `ifPresent` is always invoked, because there always is an element, even if it's an empty list (you're checking for nullity `@NonNull List<Integer> param`).
2. You're using `Optional.of` instead of `Optional.ofNullable`, so there is always going to be a non-null element.
3. Wrapping list in `Optional` does not make much sense, why not passing an empty list and not processing any elements?
4. `if(!param.isEmpty())` is redundant, because you know there are elements in the list, as stated in 3. why not passing the list for processing?
**tl;dr**: You're mixing an empty list with `null`, wrapping any collection in `Optional` does not make much sense.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论