Question

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;
       size = 0;
      
       // create empty chains
       for(int i = 0; i < numBuckets; i++){
           bucket.add(null);
       }
   }
  
   public int size(){
       return size;
   }
  
   public boolean isEmpty(){
       return size() == 0;
   }
  
   private int getBucketIndex(K key){
       // Implement Multiplicative hash
       // Assume INITIAL_VALUE = 7 HASH_MULTIPLIER = 3
   }
  
   //Adds a key value pair to hash
   public void add(K key, V value){
       // Find head of chain for given key
       // Check if key is already present
       // Insert key in chain
      
       // If load factor goes beyond threshold (0.75), then double the hash size
       // and rehash the existing items
       // print "Doubling the size, load factor > 0.75" when you double the hash size.
          
   }  
  
   // Returns value for a key
   public V get(K key){
       // Find head of chain for given key
       // Search key in chain
       // If key not found return null
      
       return null;
   }
  
   // Removes key from the hashtable
   public V remove(K key){
       // Apply hash function to find index for a given key
       // get head of the chain
       // Search for key in its chain
       // If key is found
       // Reduce size
       // Remove key and return      
       // Else keep moving in the chain
       //If key was not there return null

       return null;
      
   }
  

  

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       System.out.println("Enter the initial capacity:");
       int size = input.nextInt();
       HashtableChaining<String, Integer> hashtable = new HashtableChaining<>(size);

       System.out.println("Adding items to hashtable:");
      
       hashtable.add("FALL2017", 3);
       hashtable.add("SPRING2018", 3);
       hashtable.add("SUMMER2018", 1);
       hashtable.add("FALL2018", 4);
       hashtable.add("SPRING2019", 2);
       hashtable.add("SPRING2019", 3);

       System.out.printf("Size of the hashtable is %d%n", hashtable.size());
       System.out.println("Removing key SUMMER2018");
       System.out.printf("The value is %d%n", hashtable.remove("SUMMER2018"));
       System.out.printf("Now the size of the hashtable is %d%n",
               hashtable.size());
       System.out.println("Looking up key SUMMER2018");
       System.out.printf("The value is %s%n",
               hashtable.get("SUMMER2018"));
       System.out.printf("Is the hashtable empty? :%s%n",
               hashtable.isEmpty()? "True" : "False");

       input.close();
   }

}

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

import java.util.ArrayList;
import java.util.Scanner;

class HashNode<K, V> {
        K key;
        V value;
        HashNode<K, V> next;

        public HashNode(K key, V value) {
                this.key = key;
                this.value = value;
        }
        public HashNode(K key, V value, HashNode<K, V> next) {
                this.key = key;
                this.value = value;
                this.next = next;
        }
}

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;
                size = 0;

                // create empty chains
                for (int i = 0; i < numBuckets; i++) {
                        bucket.add(null);
                }
        }

        public int size() {
                return size;
        }

        public boolean isEmpty() {
                return size() == 0;
        }

        private int getBucketIndex(K key) {
                // Implement Multiplicative hash
                // Assume INITIAL_VALUE = 7 HASH_MULTIPLIER = 3
                return Math.abs(key.hashCode()) % numBuckets;
        }

        // Adds a key value pair to hash
        public void add(K key, V value) {
                // Find head of chain for given key
                // Check if key is already present
                // Insert key in chain
                
                // If load factor goes beyond threshold (0.75), then double the hash size
                // and rehash the existing items
                // print "Doubling the size, load factor > 0.75" when you double the hash size.
                
                if(size > 0.75 * numBuckets) {
                        ArrayList<HashNode<K, V>> oldbucket = bucket;
                        
                        bucket = new ArrayList<HashNode<K, V>>();
                        numBuckets = oldbucket.size() * 2;
                        size = 0;

                        // create empty chains
                        for (int i = 0; i < numBuckets; i++) {
                                bucket.add(null);
                        }
                        
                        for(HashNode<K, V> start : oldbucket) {
                                while(start != null) {
                                        add(start.key, start.value);
                                        start = start.next;
                                }
                        }
                }
                
                // add new node.
                if(get(key) != null) {
                        remove(key);
                }
                int index = getBucketIndex(key);
                bucket.set(index, new HashNode<>(key, value, bucket.get(index)));
                size++;
        }

        // Returns value for a key
        public V get(K key) {
                // Find head of chain for given key
                // Search key in chain
                // If key not found return null
                int index = getBucketIndex(key);
                HashNode<K, V> start = bucket.get(index);
                while(start != null) {
                        if(start.key.equals(key)) {
                                return start.value;
                        }
                        start = start.next;
                }

                return null;
        }

        // Removes key from the hashtable
        public V remove(K key) {
                // Apply hash function to find index for a given key
                // get head of the chain
                // Search for key in its chain
                // If key is found
                // Reduce size
                // Remove key and return
                // Else keep moving in the chain
                // If key was not there return null

                int index = getBucketIndex(key);
                HashNode<K, V> start = bucket.get(index);
                if(start != null) {
                        if(start.key.equals(key)) {
                                bucket.set(index, start.next);
                                size--;
                                return start.value;
                        } else {
                                HashNode<K, V> prev = start;
                                start = start.next;
                                
                                while(start != null && !start.key.equals(key)) {
                                        prev = start;
                                        start = start.next;
                                }
                                
                                if(start != null) {
                                        prev.next = start.next;
                                        size--;
                                        return start.value;
                                }
                        }
                }
                
                return null;
        }

        public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                System.out.println("Enter the initial capacity:");
                int size = input.nextInt();
                HashtableChaining<String, Integer> hashtable = new HashtableChaining<>(size);

                System.out.println("Adding items to hashtable:");

                hashtable.add("FALL2017", 3);
                hashtable.add("SPRING2018", 3);
                hashtable.add("SUMMER2018", 1);
                hashtable.add("FALL2018", 4);
                hashtable.add("SPRING2019", 2);
                hashtable.add("SPRING2019", 3);

                System.out.printf("Size of the hashtable is %d%n", hashtable.size());
                System.out.println("Removing key SUMMER2018");
                System.out.printf("The value is %d%n", hashtable.remove("SUMMER2018"));
                System.out.printf("Now the size of the hashtable is %d%n", hashtable.size());
                System.out.println("Looking up key SUMMER2018");
                System.out.printf("The value is %s%n", hashtable.get("SUMMER2018"));
                System.out.printf("Is the hashtable empty? :%s%n", hashtable.isEmpty() ? "True" : "False");

                input.close();
        }

}

please upvote.

Add a comment
Know the answer?
Add Answer to:
Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow...
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
  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • I need help fixing my java code for some reason it will not let me run...

    I need help fixing my java code for some reason it will not let me run it can someone pls help me fix it. class LinearProbingHashTable1 { private int keyname; private int valuename; LinearProbingHashTable1(int keyname, int valuename) { this.keyname = keyname; this.valuename = valuename; } public int getKey() { return keyname; } public int getValue() { return valuename; } } class LinearProbingHashTable2 { private final static int SIZE = 128; LinearProbingHashTable2[] table; LinearProbingHashTable2() { table = new LinearProbingHashTable2[SIZE]; for (int...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • 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...

  • Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly...

    Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly linked lists", as well as "hashing with chaining using doubly linked lists". Notice this program is complete except it doesn't include the remove function. Write the remove function and test it with the rest of the program including the given main program. Upload your C++ source file. ---Here is the referenced program: "hashing with chaining using singly linked lists". Below this...

  • 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...

  • Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete...

    Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete ALPQueue class (an ArrayList based priority queue) that extends the AbstractPQueue discussed in the class, along with PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class (any other implementation of above classes that are not compatible with List interface and AbstractPQueue class will not receive any credit). 2/ Task2: implement a concrete HeapPQueue class (a Heap based priority queue) that extends...

  • Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements...

    Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements DictionaryInterface<K, V> { private int numEntries; private static final int DEFAULT_CAPACITY = 5; private static final int MAX_CAPACITY = 10000; private TableEntry<K, V>[] table; private double loadFactor; private static final double DEFAULT_LOAD_FACTOR = 0.75; public HashTableOpenAddressing() { this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashTableOpenAddressing(int initialCapacity, double loadFactorIn) { numEntries = 0; if (loadFactorIn <= 0 || initialCapacity <= 0) { throw new IllegalArgumentException("Initial capacity and load...

  • You will create a class to keep student's information: name, student ID, and grade. The program...

    You will create a class to keep student's information: name, student ID, and grade. The program will have the following functionality: - The record is persistent, that is, the whole registry should be saved on file upon exiting the program, and after any major change. - The program should provide the option to create a new entry with a student's name, ID, and grade. - There should be an option to lookup a student from his student ID (this will...

  • 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 {...

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
ADVERTISEMENT