您好我试图从Map中删除对象,我正在使用assert
测试此操作// 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一起使用?
答案 0 :(得分:7)
assert
语句。你应该不在断言中加入副作用。
来自section 14.10 of the Java Language Specification:
启用或禁用断言。如果断言已启用,则断言的评估将导致对布尔表达式的求值,如果表达式求值为false,则报告错误。如果断言被禁用,则对断言的评估不会产生任何影响。
并在同一部分的讨论部分:
因为断言可能被禁用,所以程序不能假定将评估断言中包含的表达式。因此,这些布尔表达式通常应该没有副作用: