Java: Question on assert-behaviour
I have this code snippet
import java.util.ArrayList;
import java.util.List;
public class A开发者_JAVA百科ssertTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
assert(list.add("test")); //<-- adds an element
System.out.println(list.size());
}
}
Output:
0
Why is the output list empty? How does assert behave here? Thank you in advance!
You should enable assertion with -ea flag... such as;
java -ea -cp . AssertTest
Also using assertion is worst place for side effects..
Never assert on anything with side effects. When you run without asserts enabled (enabled with -ea
), list.add("test")
will not be executed.
It's a good habit to never assert anything but false, as follows:
if (!list.add("test")) {
assert false;
// Handle the problem
}
you have to enable assert. ie run as java -ea AssertTest
Incidental to your question - assertions should not contain code that is needed for the correct operation of your program, since this causes that correct operation to be dependent on whether assertions are enabled or not.
Assertions needs to be enabled. Enable them using the -ea switch.
See the Java application launcher docs.
assert method that checks whether a Boolean expression is true or false. If the expression evaluates to true, then there is no effect. But if it evaluates to false, the assert method prints the stack trace and the program aborts. In this sample implementation, a second argument for a string is used so that the cause of error can be printed.
精彩评论