Question

Implement the remove() and the rehash() methods for the following externally chained hash table. Note you...

Implement the remove() and the rehash() methods for the following externally chained hash table. Note you should rehash when "size > arraySize" at the start of the put() method. The new size of the arraySize should be "(2 * old array size) + 1"

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;

public class ExternalChainingHashTable<K,V> {
private class Mapping {
private Mapping next;
private K key;
private V value;

private Mapping(K key, V value) {
this.key = key;
this.value = value;
}
}

private static final int GOOD_ARRAY_SIZE = 1021;
private int arraySize;
private int size;
private ArrayList<LinkedList<Mapping>> bucketArray;

public ExternalChainingHashTable(int initialArraySize) {
arraySize = initialArraySize;
bucketArray = new ArrayList<>(arraySize);

for (int i = 0; i < arraySize; i++) {
bucketArray.add(new LinkedList<Mapping>());
}
}

public ExternalChainingHashTable() {
this(GOOD_ARRAY_SIZE);
}

private int hash(K key) {
// We cannot assume that hashCode is positive, so we deal with
// the negative values by computing hc % N then adding N to ensure
// that result is positive and performing % N again to ensure it is in
// range
return ((key.hashCode() % arraySize) + arraySize) % arraySize;
}

public int getSize() {
return size;
}

public double getLoad() {
return (double)size / (double) arraySize;
}

/* Maps the specified key to the specified value in this hashtable. Neither
* the key nor the value can be null.
* The value can be retrieved by calling the get method with a key that is
* equal to the original key.
* Parameters:
* key - the hashtable key
* value - the value
* Returns:
* the previous value of the specified key in this hashtable, or null if
* it did not have one
*/
public V put(K key, V value) {
if (size > arraySize) {
rehash();
}

LinkedList<Mapping> bucket = bucketArray.get(hash(key));
for (Mapping m : bucket) {
if (m.key.equals((key))) {
V oldValue = m.value;
m.value = value;
return oldValue;
}
}
bucket.add(new Mapping(key, value));
size++;
return null;
}

/* Returns the value to which the specified key is mapped, or null if this
* map contains no mapping for the key.
* More formally, if this map contains a mapping from a key k to a value v
* such that (key.equals(k)), then this method returns v; otherwise it
* returns null. (There can be at most one such mapping.)
* Parameters:
* key - the key whose associated value is to be returned
* Returns:
* the value to which the specified key is mapped, or null if this map
* contains no mapping for the key
*/
public V get(K key) {
LinkedList<Mapping> bucket = bucketArray.get(hash(key));
for (Mapping m : bucket) {
if (m.key.equals((key))) {
return m.value;
}
}
return null;
}

/* Removes the key (and its corresponding value) from this hashtable. This
* method does nothing if the key is not in the hashtable.
* Parameters:
* key - the key that needs to be removed
* Returns:
* the value to which the key had been mapped in this hashtable, or null
* if the key did not have a mapping
*/
public V remove(K key) {
// WRITE CODE HERE

}

/* Increases the capacity of and internally reorganizes this hashtable, in
* order to accommodate and access its entries more efficiently. This method
* is called automatically when the number of keys in the hashtable exceeds
* this hashtable's capacity and load factor.
* Note you should rehash when "size > arraySize" at the start of the put()
* method.
* The new size of the arraySize should be "(2 * old array size) + 1"
*/
private void rehash() {
// WRITE CODE HERE

}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;

public class ExternalChainingHashTable<K, V> {
    private class Mapping {
        private K key;
        private V value;

        private Mapping(K key, V value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return "(" + key + "," + value + ")";
        }
    }

    private static final int GOOD_ARRAY_SIZE = 1021;
    private int arraySize;
    private int size;
    private ArrayList<LinkedList<Mapping>> bucketArray;

    public ExternalChainingHashTable(int initialArraySize) {
        arraySize = initialArraySize;
        bucketArray = new ArrayList<>(arraySize);

        for (int i = 0; i < arraySize; i++) {
            bucketArray.add(new LinkedList<Mapping>());
        }
    }

    public ExternalChainingHashTable() {
        this(GOOD_ARRAY_SIZE);
    }

    private int hash(K key) {
        // We cannot assume that hashCode is positive, so we deal with
        // the negative values by computing hc % N then adding N to ensure
        // that result is positive and performing % N again to ensure it is in
        // range
        return ((key.hashCode() % arraySize) + arraySize) % arraySize;
    }

    public int getSize() {
        return size;
    }

    public double getLoad() {
        return (double) size / (double) arraySize;
    }

    /*
     * Maps the specified key to the specified value in this hashtable. Neither the
     * key nor the value can be null. The value can be retrieved by calling the get
     * method with a key that is equal to the original key. Parameters: key - the
     * hashtable key value - the value Returns: the previous value of the specified
     * key in this hashtable, or null if it did not have one
     */
    public V put(K key, V value) {
        if (size > arraySize) {
            rehash();
        }

        LinkedList<Mapping> bucket = bucketArray.get(hash(key));
        for (Mapping m : bucket) {
            if (m.key.equals((key))) {
                V oldValue = m.value;
                m.value = value;
                return oldValue;
            }
        }
        bucket.add(new Mapping(key, value));
        size++;
        return null;
    }

    /*
     * Returns the value to which the specified key is mapped, or null if this map
     * contains no mapping for the key. More formally, if this map contains a
     * mapping from a key k to a value v such that (key.equals(k)), then this method
     * returns v; otherwise it returns null. (There can be at most one such
     * mapping.) Parameters: key - the key whose associated value is to be returned
     * Returns: the value to which the specified key is mapped, or null if this map
     * contains no mapping for the key
     */
    public V get(K key) {
        LinkedList<Mapping> bucket = bucketArray.get(hash(key));
        for (Mapping m : bucket) {
            if (m.key.equals((key))) {
                return m.value;
            }
        }
        return null;
    }

    /*
     * Removes the key (and its corresponding value) from this hashtable. This
     * method does nothing if the key is not in the hashtable. Parameters: key - the
     * key that needs to be removed Returns: the value to which the key had been
     * mapped in this hashtable, or null if the key did not have a mapping
     */
    public V remove(K key) {
        LinkedList<Mapping> bucket = bucketArray.get(hash(key));
        V value = null;
        for (Mapping m : bucket) {
            if (m.key.equals((key))) {
                bucket.remove(m);
                value = m.value;
                break;
            }
        }
        return value;
    }

    /*
     * Increases the capacity of and internally reorganizes this hashtable, in order
     * to accommodate and access its entries more efficiently. This method is called
     * automatically when the number of keys in the hashtable exceeds this
     * hashtable's capacity and load factor. Note you should rehash when
     * "size > arraySize" at the start of the put() method. The new size of the
     * arraySize should be "(2 * old array size) + 1"
     */
    private void rehash() {
        ArrayList<LinkedList<Mapping>> olddata = bucketArray;
        
        arraySize = 2*arraySize + 1;
        bucketArray = new ArrayList<>(arraySize);
        
        // We again put all the data into new list
        for(LinkedList<Mapping> x: olddata) {
            for(Mapping m: x) {
                put(m.key, m.value);
            }
        }
        
        // size remains same.
    }
    

    public void print() {
        for(LinkedList<Mapping> x: bucketArray) {
            if(!x.isEmpty())
                System.out.println(x);
        }
        System.out.println();
    }
    
    public static void main(String args[]) {
        ExternalChainingHashTable<Integer, String> ec = new ExternalChainingHashTable<>();
        ec.put(1, "1");
        ec.put(2, "2");
        ec.put(3, "3");
        ec.put(4, "4");
        ec.put(1025, "10225");
        ec.put(1022, "1022");
        ec.put(1023, "1023");
        ec.print();
        
        ec.remove(1025);
        ec.print();
    }
}

**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Add a comment
Know the answer?
Add Answer to:
Implement the remove() and the rehash() methods for the following externally chained hash table. Note you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow...

    Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow the comments inside respective methods. import java.util.ArrayList; import java.util.Scanner; public class HashtableChaining<K, V> {    // Hashtable bucket    private ArrayList<HashNode<K, V>> bucket;    // Current capacity of the array list    private int numBuckets;    // current size of the array list    private int size;       public HashtableChaining(int buckets){        bucket = new ArrayList<>();        numBuckets = buckets;   ...

  • The task of this project is to implement in Java Hash Table structure using Linear Probing...

    The task of this project is to implement in Java Hash Table structure using Linear Probing Collision Strategy.   You can assume that no duplicates or allowed and perform lazy deletion (similar to BST). Specification Create a generic class called HashTableLinearProbe <K,V>, where K is the key and V is the value. It should contain a private static class, HashEntry<K,V>. Use this class to create array to represent Hashtable:             HashEntry<K,V> hashtable[]; Implement all methods listed below and test each method...

  • Java you are required to add a public Object get( Object key) method into the Hashtable...

    Java you are required to add a public Object get( Object key) method into the Hashtable class. As defined in the Java documentation, the get() method returns the value with which the specified key is associated, or null if this hash table contains no record for the key. More formally, if this hash table contains a mapping from a key k to a value v such that (key.equals(k)), then this method returns v; otherwise it returns null. (There can be...

  • IN JAVA LANGUAGE: For this lab you are required for implement the following methods: 1. public...

    IN JAVA LANGUAGE: For this lab you are required for implement the following methods: 1. public QuadraticProbingHashTable( int size ): As the signature of this method suggests, this is a constructor for this class. This constructor will initialize status of an object from this class based on the input parameter (i.e., size). So, this function will create the array HashTable with the specified size and initialize all of its elements to be null. 2. public int hash(int value, int tableSize...

  • Java Quadratic Probing Hash table HELP! Complete the Map and Entry class provided in Map.java. Create...

    Java Quadratic Probing Hash table HELP! Complete the Map and Entry class provided in Map.java. Create a tester/driver class to show the Map class is working as intended. Methods/Constructor correctly completed (2pt) This is the Map class methods Map(), put(key, value), get(key), isEmpty(), makeEmpty() Private class correctly completed (2pt) This is the Entry class methods Add the methods that are required for this to work correctly when stored in the QuadraticProbingHashTable Tester class (1pt) Show the methods of the Map...

  • Write a method in the HashIntSet class called addAll that accepts another hash set as a...

    Write a method in the HashIntSet class called addAll that accepts another hash set as a parameter and adds all of the elements from the other set into the current set. For example, if the set stores [-5, 1, 2, 3] and the method is passed [2, 3, 6, 44, 79], your set would store [-5, 1, 2, 3, 6, 44, 79]. Write a method in the HashIntSet class called containsAll that accepts another hash set as a parameter and...

  • Type up and get the Hash table on pages 19 - 22 to work. Show your...

    Type up and get the Hash table on pages 19 - 22 to work. Show your sample test run at the bottom of your code using a multiline comment I typed everything but the code is not working please help me fix the mistakes. These are pages 19-22. The code I have: #include <iostream> #inlcude <iomanip> #include <stack> #include <vector> #include <cstdlib> #include <ctime> using namespace std; //////////////////////////////HASH TABLE/////////////////////////////////////////////// //hash.cpp //demonstrate hash table with linear probing /////////////////////////////////////////////////////////////////////////////////////// class DataItem {...

  • Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

    Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases). Theory answer Here Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This...

  • Implement an eager delete() method for linear probing hash table. The eager delete will delete the...

    Implement an eager delete() method for linear probing hash table. The eager delete will delete the pair from the hash table, not just set the value to null. *Algorithhms* In Java Language Please I want to add the delete method to this hash table code. public class Linear ProbingHashST<Key, Value> private int M = 30001; private Value [] vals = (Value[]) new Object[M]: private Key [] keys = (Key []) new Object[M]: array doubling and halving code omitted private int...

  • JAVA Submit:    HashSet.java    with the following methods added: HashSet.java // Implements a set of...

    JAVA Submit:    HashSet.java    with the following methods added: HashSet.java // Implements a set of objects using a hash table. // The hash table uses separate chaining to resolve collisions. // Original from buildingjavaprograms.com supplements public class HashSet<E> { private static final double MAX_LOAD_FACTOR = 0.75; private HashEntry<E>[] elementData; private int size; // Constructs an empty set. @SuppressWarnings("unchecked") public HashSet() { elementData = new HashEntry[10]; size = 0; } // ADD METHODS HERE for exercise solutions: // Adds the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT