edu.princeton.cs.algs4
Class Bag<Item>
- java.lang.Object
-
- edu.princeton.cs.algs4.Bag<Item>
-
- Type Parameters:
Item- the generic type of an item in this bag
- All Implemented Interfaces:
- java.lang.Iterable<Item>
public class Bag<Item> extends java.lang.Object implements java.lang.Iterable<Item>TheBagclass 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
LinkedBagfor the version from the textbook that uses a non-static nested class. SeeResizingArrayBagfor 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.
-
-
Constructor Summary
Constructors Constructor and Description Bag()Initializes an empty bag.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method and Description voidadd(Item item)Adds the item to this bag.booleanisEmpty()Returns true if this bag is empty.java.util.Iterator<Item>iterator()Returns an iterator that iterates over the items in this bag in arbitrary order.static voidmain(java.lang.String[] args)Unit tests theBagdata type.intsize()Returns the number of items in this bag.
-
-
-
Method Detail
-
isEmpty
public boolean isEmpty()
Returns true if this bag is empty.- Returns:
trueif this bag is empty;falseotherwise
-
size
public int size()
Returns the number of items in this bag.- Returns:
- the number of items in this bag
-
add
public void add(Item item)
Adds the item to this bag.- Parameters:
item- the item to add to this bag
-
iterator
public java.util.Iterator<Item> iterator()
Returns an iterator that iterates over the items in this bag in arbitrary order.- Specified by:
iteratorin interfacejava.lang.Iterable<Item>- Returns:
- an iterator that iterates over the items in this bag in arbitrary order
-
main
public static void main(java.lang.String[] args)
Unit tests theBagdata type.- Parameters:
args- the command-line arguments
-
-
DataMelt 3.0 © DataMelt by jWork.ORG