FileDocCategorySizeDatePackage
BagExample.javaAPI DocExample3764Wed May 18 09:38:58 BST 2005com.discursive.jccook.collections.bag

BagExample

public class BagExample extends Object

Fields Summary
org.apache.commons.collections.Bag
inventoryBag
Album
album1
Album
album2
Album
album3
Album
album4
Constructors Summary
Methods Summary
private voidcheckout(org.apache.commons.collections.Bag shoppingCart, java.lang.String customer)

		// Check to see if we have the inventory to cover this purchase
		if( inventoryBag.containsAll( (Collection) shoppingCart ) ) {
			// Remove these items from our inventory
			inventoryBag.removeAll( (Collection) shoppingCart );
			System.out.println( customer + " purchased the following items:" );
			printAlbums( shoppingCart );
		} else {
			System.out.println( customer + ", I'm sorry but we are unable to fill your order." );
		}
		printSeparator();
	
public static voidmain(java.lang.String[] args)


	     
		BagExample example = new BagExample();
		example.start();
	
private voidpopulateInventory()

		inventoryBag.add( album1, 200 );
		inventoryBag.add( album2, 100 );
		inventoryBag.add( album3, 500 );
		inventoryBag.add( album4, 900 );
	
private voidprintAlbums(org.apache.commons.collections.Bag albumBag)

		Set albums = albumBag.uniqueSet();
		Iterator albumIterator = albums.iterator();
		while( albumIterator.hasNext() ) {
			Album album = (Album) albumIterator.next();
			NumberFormat format = NumberFormat.getInstance();
			format.setMinimumIntegerDigits( 3 );
			format.setMaximumFractionDigits( 0 );
			System.out.println( "\t" +  
				format.format( albumBag.getCount( album ) ) + " - " + album.getBand()  );
		}
	
private voidprintSeparator()

		System.out.println( StringUtils.repeat( "*", 65 ) );
	
private voidstart()

		// Read our inventory into a Bag
		populateInventory();

		System.out.println( "Inventory before Transactions" );
		printAlbums( inventoryBag );
		printSeparator();

		// A Customer wants to purchase 400 copies of ABBA and 2 copies of Radiohead
		Bag shoppingCart1 = new HashBag();
		shoppingCart1.add( album4, 500 );
		shoppingCart1.add( album3, 150 );
		shoppingCart1.add( album1, 2 );
		checkout( shoppingCart1, "Customer 1" );
		
		// Another Customer wants to purchase 600 copies of ABBA 
		Bag shoppingCart2 = new HashBag();
		shoppingCart2.add( album4, 600 );
		checkout( shoppingCart2, "Customer 2" );		

		// Another Customer wants to purchase 3 copies of Kraftwerk
		Bag shoppingCart3 = new HashBag();
		shoppingCart3.add( album2, 3 );
		checkout( shoppingCart3, "Customer 3" );		

		System.out.println( "Inventory after Transactions" );
		printAlbums( inventoryBag );