Package

org.taffy.core.container

Object Hierarchy
What is it?

A Hash is a container that maps keys to values. It provides fast lookup, insertion and deletion.

Quick Example
hash = (1 => "one", 2 => "two")



Table of Contents:

Constructing a Hash

A Hash is created by enclosing key-value pairs inside a set of parentheses. Key-value pairs follow the format:

key => value

The keys and values are arbitrary — any key may be mapped to any value.

// create hash mapping "1" to 1, and "2" to 2
hash = (1 => "1", 2 => "2")

// create the same hash, but each key-value pair is on a separate line
hash = (1 => "1",
        "2" => 2)

// create an empty hash and add items to it
hash = ()
hash[1] = "1"
hash[2] = "2"

Setting and Getting

To set a value use the []= operator or the setValue:forKey: method.

// create hash that maps 1 to "1", and 2 to "2'
myHash = ()
myHash[1] = "1"
myHash setValue: "2" forKey: 2

To get a value use the [] operator or the objectForKey: method. If a value for the key does not exist, nil is returned.

myHash = (1 => "1", 2 => "2")

myHash[1]
==> "1"

myHash objectForKey: 2
==> "2"

myHash[3]
==> nil

Iterating an Hash

The elements of an array can be iterated by using one of three methods: each:, eachKey: or eachValue:. The each: method executes the given block and passes each key-value pair as a Pair to it. The eachKey: method executes the given block and passes each key to it. And the eachValue: method executes the given block and passes each value to it.

hash = (1 => 2, 3 => 4)

// print each key-value pair
hash each: { <pair>
    io putLine: pair
}

==> #Pair<3, 4>
==> #Pair<1, 2>

// print the values
hash eachValue: { <value>
    io putLine: value
}

// 4 and 2 are output
==> 4
==> 2

// print the keys
hash eachKey: { <key>
    io putLine: key
}

==> 3
==> 1

Hashing Keys

A Hash obtains a hash value of a key by calling its hash method. The hash method of an object must return a whole Number, otherwise an exception will be thrown when attempting to use the object as a key.

Overwriting Values

Each key in a Hash has a distinct hash value. This means that the same key can only map to a single value. If the same key is used to update the Hash with a new key-value pair, the new key-value pair is used:

hash = (1 => 2)
==> #Hash(1 => 2)

// overwrite it
hash[1] = 3

==> #Hash(1 => 3)