gpt4 book ai didi

Java 8 optional 添加仅当 optional.isPresent 时才返回结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:28:09 24 4
gpt4 key购买 nike

我有一段代码,其中一个接口(interface)有一个可选的返回方法,一些实现它的类返回一些东西,其他的则没有。

为了拥抱这个出色的“空 killer ”,我尝试了以下方法:

public interface Gun {
public Optional<Bullet> shoot();
}

public class Pistol implements Gun{
@Override
public Optional<Bullet> shoot(){
return Optional.of(this.magazine.remove(0));
}//never mind the check of magazine content
}

public class Bow implements Gun{
@Override
public Optional<Bullet> shoot(){
quill--;
return Optional.empty();
}
}

public class BallisticGelPuddy{
private Gun[] guns = new Gun[]{new Pistol(),new Bow()};
private List<Bullet> bullets = new ArrayList<>();
public void collectBullets(){
//here is the problem
for(Gun gun : guns)
gun.shoot.ifPresent(bullets.add( <the return I got with the method>)
}}

对于这个例子的愚蠢,我深表歉意。
我如何检查我刚刚获得的返回并仅在存在时添加它,使用可选?

附言Optional 是否真的有用,而 if(X != null) 做不到?

最佳答案

我明白你的意思了——当弹丸(可能是比 Bullet 更好的类名)通过 BallisticGelPuddy 时,它要么被卡住,要么没有。如果卡住了,它会累积在 BallisticGelPuddy 中。

如果我们改用 null 检查,让我们重写代码:

for(Gun gun: guns) {
final Bullet bullet = gun.shoot();
if(bullet != null) {
bullets.add(bullet);
}
}

很简单,对吧?如果存在,我们要将其添加进去。

让我们重新添加可选样式:

for(Gun gun: guns) {
gun.shoot().ifPresent(bullets::add);
}

尽管 Optional 方法更简洁,但实际上这两件事完成的是同一件事。

在这种情况下,这两种方法之间确实没有区别,因为您总是要检查是否存在。 Optional 旨在防止在处理 null 时出错,并允许您 express a more fluid call chain ,但请考虑在这种情况下使用 Optional 的实用性。对于这种情况,它似乎并不完全是必要的

关于Java 8 optional 添加仅当 optional.isPresent 时才返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37846407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com