Java assert disables execution of Map.remove()
Hi i was trying to remove object from Map and i was testing this operation using 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);
aforementioned methods were tested on开发者_StackOverflow same data. Why Map.remove() does not work with assert?
assert
statements either execute or not based on how you start the VM. You should not put side-effects in assertions.
From 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.
and in the discussion part of the same section:
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:
精彩评论