gpt4 book ai didi

Java 断言禁用 Map.remove() 的执行

转载 作者:行者123 更新时间:2023-11-29 06:44:29 25 4
gpt4 key购买 nike

您好,我正在尝试从 Map 中删除对象,并且我正在使用断言测试此操作

// definition of map 
private Map<String, Map<Long, Object>> groups = new HashMap<String, Map<Long, Object>>();

// this does not remove item from map
assert groups.get("key").remove(id) != null;

// this removes item from map
groups.get("key").remove(id);

上述方法在相同的数据上进行了测试。为什么 Map.remove() 不适用于断言?

最佳答案

assert 语句根据您启动 VM 的方式执行或不执行。您不应该在断言中加入副作用。

来自 section 14.10 of the Java Language Specification :

An assertion is either enabled or disabled. If the assertion is enabled, evaluation of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, evaluation of the assertion has no effect whatsoever.

在同一节的讨论部分:

Because assertions may be disabled, programs must not assume that the expressions contained in assertions will be evaluated. Thus, these boolean expressions should generally be free of side effects:

关于Java 断言禁用 Map.remove() 的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288066/

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