/// <summary> /// CONSTRUCTOR /// </summary> /// public OpenAddressingHashTable(int size) { _size = size; _loadFactor = 0.40; _inTable = 0; _table = new OAHashEntry <TKey, TValue> [_size]; _keys = new List <TKey>(); _values = new List <TValue>(); //initialize all values to -1 for (int i = 0; i < _table.Length; i++) { //initialize each slot _table[i] = new OAHashEntry <TKey, TValue>(default(TKey), default(TValue), false); } }
public void Add(TKey key, TValue value) { int i = 0; //makes sure there are no duplicate keys if (ContainsKey(key)) { return; } do { //calculate index int index = _double_hash(key, i); if (_table[index].occupied == false) { var newEntry = new OAHashEntry <TKey, TValue>(key, value, true); _keys.Add(key); _values.Add(value); //set value and key _table[index] = newEntry; //increment how many items are in the table _inTable++; break; } else { i++; } } while (i != _size); //every slot is in the table is occupied if (_inTable == _size) { //expand and rehash _expand(); } }
//rehashes table private void _rehash() { //will hold contents of _table to copy over OAHashEntry <TKey, TValue>[] temp = new OAHashEntry <TKey, TValue> [_size]; temp = _table; OAHashEntry <TKey, TValue>[] rehash = new OAHashEntry <TKey, TValue> [_size]; for (int i = 0; i < rehash.Length; i++) { //initialize each slot rehash[i] = new OAHashEntry <TKey, TValue>(default(TKey), default(TValue), false); } _inTable = 0; _table = rehash; //rehash over the newly sized table for (int i = 0; i < temp.Length; i++) { //this should rehash since the size is now doubled so the hashing will be different //inserts the key into _table Add(temp[i].key, temp[i].value); } }