View Javadoc
1   import java.util.ArrayList;
2   import java.util.List;
3
4   public class AssertionsWithSideEffects {
5       public static int iinc(int x) {
6           assert x++ == 0;
7           return x;
8       }
9
10      public static boolean storeBoolean(boolean b) {
11          boolean y = false;
12          assert y = b == true;
13          return y;
14      }
15
16      public static boolean storeInt(int n) {
17          boolean y = false;
18          assert y = (n == 1);
19          return y;
20      }
21
22      private static List<String> list = new ArrayList<String>();
23
24      public static void addAndRemove() {
25          list.add("a");
26          assert list.remove(null);
27      }
28
29      public static void addAndCheckEmptiness() {
30          list.add("a");
31          assert !list.isEmpty();
32      }
33
34      // A sample immutable class with an "add" operation
35      private static class ImmutableList<Element> {
36          Object[] elements;
37
38          public ImmutableList() {
39              elements = new Object[0];
40          }
41
42          private ImmutableList(Object[] array, Element e) {
43              elements = new Object[array.length + 1];
44              System.arraycopy(array, 0, elements, 0, array.length);
45              elements[array.length] = e;
46          }
47
48          // Does not mutate the current object but creates a new one
49          public ImmutableList<Element> add(Element e) {
50              return new ImmutableList<Element>(elements, e);
51          }
52
53          public boolean isEmpty() {
54              return elements.length == 0;
55          }
56      }
57
58      private static ImmutableList<String> il = new ImmutableList<>();
59
60      public static void add() {
61          assert !il.add("a").isEmpty();
62      }
63  }