import java.util.Map; import java.util.TreeMap; class MultiSet { private Map counts; public MultiSet( ) { counts = new TreeMap( ); } public String toString( ) { return counts.toString( ); } public int size( ) { int total = 0; for( Integer occurs : counts.values( ) ) total += occurs; return total; } public void add( String x ) { Integer occurs = counts.get( x ); if( occurs == null ) counts.put( x, 1 ); else counts.put( x, occurs + 1 ); } // Remove an item. // If x is not found, return false. // If x is present with count 1, remove it from the map. // If x is present with count > 1, drop count public boolean remove( String x ) { Integer occurs = counts.get( x ); if( occurs == null ) return false; if( occurs == 1 ) counts.remove( x ); else counts.put( x, occurs - 1 ); return true; } public boolean contains( String x ) { return counts.get( x ) != null; } } class Exam4 { public static void main( String [ ] args ) { MultiSet m = new MultiSet( ); m.add( "hello" ); m.add( "world" ); m.add( "zebra" ); m.add( "hello" ); System.out.println( m ); System.out.println( m.contains( "hello" ) ); System.out.println( m.contains( "oops" ) ); System.out.println( m.size( ) ); m.remove( "zebra" ); m.remove( "hello" ); System.out.println( m ); } }