Question

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 through main method.
    • Public Boolean insert (K key, V value)
      • This function inserts entry, rehashes if the table is full, throw error message if the key is invalid or null and return true upon successful insertion or false if duplicate entry
    • Public V find (K key)
      • This function check if the key exists in the table. If yes, true value of the key, or null if not found
    • Public Boolean delete (K key)
      • Performs lazy deleting by marking the entry as deleted. Return true if deleted , false if it not found in the hashtable
    • Public int getHashValue(K key)
      • Returns the hash value for the given key or return -1 if not found
    • Private void rehash()
      • If the table is full, then doubles the hash table size, rehash everything to the new table, ignore items marked deleted.
    • Public static void main(String args[])
      • Methods calls to demonstrate functionality of methods above. Make sure to check with both Integer and String objects
  • You may use the pseudocode provide in the text, but make sure to have exception handling for invalid input parameters and method calls.

Please write this in JAVA and provide screenshot of output. Answer question correctly.

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

ScreenShot:


Code:


/**
*
* Hash table implementation with linear probing.
*
*
* @param <K>
* @param <V>
*/
public class HashTableLinearProbe<K, V> {

   // initial size of array
   private static final int INITIAL_CAPACITY = 3;

   private int capacity = INITIAL_CAPACITY;
   // counts the entries in hashtable
   private int size = 0;

   // This holds actual key value pair
   public static class HashEntry<K, V> {

       private K key;
       private V value;
       // lazy delete
       private boolean deleted;

       public HashEntry(K key, V value) {
           this.key = key;
           this.value = value;
       }

       public K getKey() {
           return key;
       }

       public V getValue() {
           return value;
       }

   }// HashEntry class ends

   // hold the hashtable entries
   private HashEntry<K, V> hashtable[];

   @SuppressWarnings("unchecked")
   // HashTableLinearProbe constructor
   public HashTableLinearProbe() {

       // initialize the hashtable with initial capacity
       this.hashtable = new HashEntry[INITIAL_CAPACITY];

   }// HashTableLinearProbe constructor ends

   // inserts key value in hashtable
   public Boolean insert(K key, V value) {

       if (key == null) {
           throw new IllegalArgumentException("Null key now allowed");
       }

       // check if resize is needed.
       if (size >= capacity) {
           rehash();
       }

       int i;

       // if key passed is equal to hashtable entry key then return false
       for (i = getHashValue(key); hashtable[i] != null; i = (i + 1) % capacity) {

           if (hashtable[i].equals(key)) {
               return false;
           }

       }

       // initialize entry
       HashEntry<K, V> entry = new HashEntry<>(key, value);

       // inserts entry
       hashtable[i] = entry;

       // increase size
       size++;

       // confirm the increament
       return true;

   } // insert() ends

   // find the value by key in hashtable
   public V find(K key) {

       if (key == null) {

           throw new IllegalArgumentException("Key cannot be null");
       }

       // checks passed key is equal to hashtable entry key
       for (int i = getHashValue(key); hashtable[i] != null; i = (i + 1) % capacity) {

           if (hashtable[i].key.equals(key) && !hashtable[i].deleted) {
               // value found
               return hashtable[i].value;
           }

       }

       // confirms no value was found
       return null;

   }// find() ends

   // delete entry by key
   public Boolean delete(K key) {

       if (key == null) {
           throw new IllegalArgumentException("Invalid key");
       }

       int i = getHashValue(key);

       // if entry is null then value doesn't exists
       if (hashtable[i] == null) {
           return false;
       }

       // compares and get index of passed key in hashtable
       while (!key.equals(hashtable[i].key)) {
           i = (i + 1) % capacity;
       }

       hashtable[i].deleted = true;
       size--;

       return true;

   }// delete() ends

   // gets the array index
   public int getHashValue(K key) {

       if (key == null || key.hashCode() == 0) {
           return -1;
       }

       // mod with capacity is done to get the value within length of hashtable
       return key.hashCode() % capacity;

   }// getHashValue() ends

   @SuppressWarnings("unchecked")
   // resizes the hastable to double when it's full
   private void rehash() {

       // tmperory hashtable array
       HashEntry<K, V> tmp[] = new HashEntry[2 * capacity];

       // shifts all value from hashtable to tmp
       for (int i = 0; i < capacity; i++) {

           if (hashtable[i] != null && !hashtable[i].deleted ) {
               tmp[i] = hashtable[i];
           }

       }

       // points hashtable to new hashtable i.e tmp
       hashtable = tmp;

       // marks the increase in capacity by 2
       capacity = 2 * capacity;

   }

   public static void main(String[] args) {

       HashTableLinearProbe<String, String> htlp = new HashTableLinearProbe<>();

       System.out.println("Initial capacity " + htlp.hashtable.length);

       System.out.println("(S1,V1) added " + htlp.insert("S1", "V1"));
       System.out.println("(S2,V2) added " + htlp.insert("S2", "V2"));
       System.out.println("(S3,V3) added " + htlp.insert("S3", "V3"));
       System.out.println("(S4,V4) added " + htlp.insert("S4", "V4"));

       System.out.println("capacity after rehashing " + htlp.hashtable.length);

       System.out.println("Find S1 ->" + htlp.find("S1"));

       System.out.println("Delete S1 ->" + htlp.delete("S1"));
       System.out.println("Find S1 ->" + htlp.find("S1"));

   }

}

Add a comment
Know the answer?
Add Answer to:
The task of this project is to implement in Java Hash Table structure using Linear Probing...
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;   ...

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

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

  • Identify the letters and anything associated with it. It is a hash map so please feel...

    Identify the letters and anything associated with it. It is a hash map so please feel free to point out the other important parts beside the arrows. I apologize for the order of the pictures class HashMap private: HashEntry table ; public: HashMap() table-new HashEntry * [TABLE_SIZE]; for (int 1-0; 1< TABLE SIZE: i++) table [i] = NULL; Hash Function int HashFunc(int key) return key % TABLE-SIZE; Insert Element at a key void Insert(int key, int value) int hashHashFunc(key); while...

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

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

  • JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main...

    JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main if possible. those are just the sample HashIntSet and HashMain (don't have to be the same but follow the Q requirement. thanks HashIntSet.java public class HashIntSet { private static final double MAX_LOAD_FACTOR = 0.75; private HashEntry[] elementData; private int size; // Constructs an empty set. public HashIntSet() { elementData = new HashEntry[10]; size = 0; } // Adds the given element to...

  • This should be in Java Create a simple hash table You should use an array for...

    This should be in Java Create a simple hash table You should use an array for the hash table, start with a size of 5 and when you get to 80% capacity double the size of your array each time. You should create a class to hold the data, which will be a key, value pair You should use an integer for you key, and a String for your value. For this lab assignment, we will keep it simple Use...

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

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

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