Class Bag<Item>

  • Type Parameters:
    Item - the generic type of each item in this bag
    All Implemented Interfaces:

    public class Bag<Item>
    extends Object
    implements Iterable<Item>
    The Bag class represents a bag (or multiset) of generic items. It supports insertion and iterating over the items in arbitrary order.

    This implementation uses a singly linked list with a static nested class Node. See LinkedBag for the version from the textbook that uses a non-static nested class. See ResizingArrayBag for a version that uses a resizing array. The add, isEmpty, and size operations take constant time. Iteration takes time proportional to the number of items.

    For additional documentation, see Section 1.3 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.

    Robert Sedgewick, Kevin Wayne
    • Constructor Detail

      • Bag

        public Bag()
        Initializes an empty bag.
    • Method Detail

      • isEmpty

        public boolean isEmpty()
        Returns true if this bag is empty.
        true if this bag is empty; false otherwise
      • size

        public int size()
        Returns the number of items in this bag.
        the number of items in this bag
      • add

        public void add​(Item item)
        Adds the item to this bag.
        item - the item to add to this bag
      • iterator

        public Iterator<Item> iterator()
        Returns an iterator that iterates over the items in this bag in arbitrary order.
        Specified by:
        iterator in interface Iterable<Item>
        an iterator that iterates over the items in this bag in arbitrary order
      • main

        public static void main​(String[] args)
        Unit tests the Bag data type.
        args - the command-line arguments