0

I have this code snippet

import java.util.ArrayList;
import java.util.List;

public class AssertTest {
    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!

3
  • yes, it does. I just activated the -ea flag and it outputs 1. Commented Mar 22, 2011 at 9:30
  • ok - add() returns a boolean. something I didn't know and I still don't want to know. such return type is just silly. if a subtype of Collection needs to provide such function, the subtype can add a new method. Commented Mar 22, 2011 at 9:36
  • The fact that add() returns a boolean might be useful when using HashSet<?>. If you try to add a value having the same hash code as one contained in the set, the add() method will return false. You can also think of Collection<?>s allowing only n values. So the return value is fully justified. Commented Mar 24, 2011 at 11:59

6 Answers 6

5

You should enable assertion with -ea flag... such as;

java -ea -cp . AssertTest

Also using assertion is worst place for side effects..

Sign up to request clarification or add additional context in comments.

1 Comment

plus, never use the side-effects of assert expressions in your application!
5

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
}

Comments

0

you have to enable assert. ie run as java -ea AssertTest

Comments

0

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.

Comments

0

Assertions needs to be enabled. Enable them using the -ea switch.

See the Java application launcher docs.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.