src/com/michaelho/RandomizedAlgorithms/RA3.java
// Adds a key value pair to hash
Adds a key value pair to hash
Adds a key value pair to hash
public void add(K key, V value) {
            int bucketIndex = hash(key);
            HashNode<K, V> head = bucketArray.get(bucketIndex);
            while (head != null) {
                if (head.key.equals(key)) {
                    head.value = value;
                    return;
                }
                head = head.next;
            }
            size++;
            head = bucketArray.get(bucketIndex);
            HashNode<K, V> newNode = new HashNode<>(key, value);
            newNode.next = head;
            bucketArray.set(bucketIndex, newNode);
            if ((1.0 * size) / numBuckets >= loadThreshold) {
                ArrayList<HashNode<K, V>> temp = bucketArray;
                bucketArray = new ArrayList<>();
                numBuckets = 2 * numBuckets;
                size = 0;
                for (int i = 0; i < numBuckets; i++)
                    bucketArray.add(null);
                for (HashNode<K, V> headNode : temp) {
                    while (headNode != null) {
                        add(headNode.key, headNode.value);
                        headNode = headNode.next;
                    }
                }
            }
        }
public void add ( K key , V value ) { int bucketIndex = hash ( key ) ; HashNode < K , V > head = bucketArray . get ( bucketIndex ) ; while ( head != null ) { if ( head . key . equals ( key ) ) { head . value = value ; return ; } head = head . next ; } size ++ ; head = bucketArray . get ( bucketIndex ) ; HashNode < K , V > newNode = new HashNode < > ( key , value ) ; newNode . next = head ; bucketArray . set ( bucketIndex , newNode ) ; if ( ( 1.0 * size ) / numBuckets >= loadThreshold ) { ArrayList < HashNode < K , V > > temp = bucketArray ; bucketArray = new ArrayList < > ( ) ; numBuckets = 2 * numBuckets ; size = 0 ; for ( int i = 0 ; i < numBuckets ; i ++ ) bucketArray . add ( null ) ; for ( HashNode < K , V > headNode : temp ) { while ( headNode != null ) { add ( headNode . key , headNode . value ) ; headNode = headNode . next ; } } } }
Adds a key value pair to hash
Adds a key value pair to hash
// Check if key is already present, replace the old value if it exists. // Insert key in chain // If load factor goes beyond threshold, then double hash table size