I have a class for my MultiSet<E>, and an associated test-program.
My class is a follows:
public class MultiSet<E> extends AbstractCollection<E> { private int size = 0; private Map<E, Integer> values = new HashMap<E, Integer>(); public MultiSet() { } public MultiSet(Collection<E> c) { addAll(c); } @Override public boolean add(E e) { Integer i = values.get(e); if (i == null) values.put(e, 1); else values.put(e, i + 1); return true; } @Override public boolean remove(Object o) { Integer i = values.remove(o); return i != null; } public Iterator<E> iterator() { return new Iterator<E>() { private Iterator<E> iterator = values.keySet().iterator(); private int remaining = 0; private E current = null; public boolean hasNext() { return remaining > 0 || iterator.hasNext(); } public E next() { if (remaining == 0) { current = iterator.next(); remaining = values.get(current); } remaining--; return current; } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null) return false; if (this.getClass() != object.getClass()) return false; MultiSet<?> o = (MultiSet<?>) object; return o.values.equals(values); } @Override public int hashCode() { return values.hashCode()*163 + new Integer(size).hashCode()*389; } @Override public String toString() { String res = ""; for (E e : values.keySet()) { res = res + "[" + e.toString() + ":" + values.get(e) + "]"; } return getClass().getName() + res; } public int size() { return values.size(); } }
And the test program:
public class MultiSetTest { public static void main(String[] args) { MultiSet<String> a = new MultiSet<String>(); MultiSet<String> b = new MultiSet<String>(); a.add("Foo"); a.add("Bar"); a.add("Foo"); System.out.println("a:" + a); // test toString b.add("Bar"); b.add("Foo"); b.add("Bar"); b.add("Foo"); System.out.println("b:" + b); assert !a.equals(b) : "Failed test 1!"; // test equals assert b.remove("Bar") : "Failed test 2!"; // test remove assert a.equals(b) : "Failed test 3!"; for(String s : a) { // test iterator assert b.remove(s) : "Failed test 4!"; } assert b.size() == 0 : "Failed test 5!"; Set<String> baseSet = new HashSet<String>(a); assert baseSet.size()==2 : "Failed test 6!"; b = new MultiSet<String>(a); assert a.equals(b) : "Failed test 7!"; try { assert false; System.out.println("Please enable assertions!"); } catch(AssertionError e) { System.out.println("Success!"); } } }
To me it seems to be working, but if my MultiSet-class was working proberly, then the output should be: "Success!"
Instead i get: "Please enable assertions!".
Where/how do i enable assertions?