gpt4 book ai didi

java - 如果元素存在,Set.remove 是否可能返回 false?

转载 作者:行者123 更新时间:2023-11-29 07:30:37 43 4
gpt4 key购买 nike

考虑以下示例:

public Optional<User> getUser(Integer id) {
for(User user : usersSet) {
if(user.getId().equals(id)) return Optional.of(user);
}
return Optional.empty();
}

public void deleteUser(Integer id) {
User user = getUser(id).orElseThrow(new RuntimeException("User not found"));
boolean result = usersSet.remove(user);
}

是否存在结果为假的情况?

我问是因为我不知道是否有必要检查 HashSet 的 remove 方法的结果。

最佳答案

没有。如果元素存在,则无法得到 false。

如果您查看 docs , 明确提到。

true if this set contained the specified element

关于java - 如果元素存在,Set.remove 是否可能返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343111/

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