Bag:
Filter:
Classes | Collections > Unordered

Bag : Collection : Object

Unordered collection of objects
Source: Bag.sc
Subclasses: IdentityBag

Description

A Bag is an unordered collection of objects. In some languages it is referred to as a counted set. A Bag keeps track of the number of times objects are inserted and requires that objects be removed the same number of times. There is only one instance of an object in a Bag even if the object has been added to the Bag multiple times (test is for equality)

Most of Bag's methods are inherited from Collection. The contents of a Bag are unordered. You must not depend on the order of items in a set.

Class Methods

Bag.new(n: 4)

Creates a Bag with an initial capacity for n objects.

Inherited class methods

Instance Methods

.contents

Returns the dictionary that stores the objects in pairs (obj -> numberOfObjects)

Returns:

.itemCount(item)

Count the number of items.

Adding and Removing

.add(item, count: 1)

Add an object to the Bag. A Bag may contain multiple entries of the same object.

.remove(item, count: 1)

Remove an object from the Bag.

Iteration

.do(function)

Evaluates function for each item in the Bag. The function is passed two arguments, the item and an integer index.

Arguments:

function

args to function: item, i

.countsDo(function)

Evaluates function for each unique item in the Bag along with that item's count. The function is passed two arguments, the item, the quantity of that item in the Bag and an integer index.

Testing

.includes(item)

Answer whether an object is contained in the Bag.

Returns:

Inherited instance methods

Undocumented instance methods

.asBag

.at

.atFail

.choose

.put

.take

.wchoose

Examples

Difference between Bag and IdentityBag: