Question

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 at most one such mapping.)

import java.util.LinkedList;

public class Hashtable {
   private class HashtableRecord{
       private Object key;
       private Object value;

       public HashtableRecord() {
           this.key = null;
           this.value = null;
       }

       public HashtableRecord(Object inKey, Object inData) {
           this.key = inKey;
           this.value = inData;
       }

       /* Equality can be based on key alone because there can't be
       * 2 records with the same key in the table */
       public boolean equals(Object obj) {
           if (obj instanceof HashtableRecord) {
               HashtableRecord node = (HashtableRecord)obj;
               return this.key.equals(node.key);
           }
           else {
               return false;
           }
       }

       public String toString() {
           return "Key: ["+this.key+"] Value: ["+this.value+"]";
       }
   }
   //
   //
   private final int tableSize = 101;
   private int numElements;
   private Object [] table;
  
   //constructor
   public Hashtable(int realSize) {
       this.table = new Object[realSize];
       this.numElements = 0;
   }
  
   public Hashtable() {
       this.table = new Object[this.tableSize];
       this.numElements = 0;
   }
  
   private int hash(Object key) {

       /* Start with a base, just so that it's not 0 for empty strings */
       int result = 42; //start at hard coded base

       String inputString = key.toString().toLowerCase();
       //System.out.println("hash string is:" + inputString + "\n");

       char [] characters = inputString.toCharArray();
       for (int i = 0; i < characters.length; i++) {
           char currentChar = characters[i];
           int j = (int)currentChar;
           //System.out.println("j = " + j );
           result += j;
       }
       return (result % this.table.length);
   }

   public void put(Object key, Object data) {
       if (data == null || key == null) {
           System.err.println("ERROR: Either the key or the data are null");
           return;
       }

       // If trying to add duplicate keys, that means
       // we like to update the value associated with that existing key.
       // We first delete the existing mapping, then insert a new record that key.
       if (this.contains(key)) {
           remove(key);
       }
       // Find out where in our array should the new item goes
       int pos = this.hash(key);
       // If nothing exists in the position, create a new linked list there
       if (this.table[pos] == null) {
           this.table[pos] = new LinkedList<HashtableRecord>();
       }
      
       LinkedList<HashtableRecord> theList = (LinkedList<HashtableRecord>) this.table[pos];
       // Add to the linked list in the appropriate position
       theList.add(new HashtableRecord(key, data));
       this.numElements++;
   }
  
   public void put(Object [] keys, Object [] inputData) {
       for (int i = 0; i < inputData.length; i++) {
           this.put(keys[i], inputData[i]);
       }
   }
  
public Object get(Object key)
{
  
return null; // change this as needed.
}

   //return type is different from the standard Map interface.
   public void remove(Object key) {
       int pos = this.hash(key);

       if (this.table[pos] != null) {
           HashtableRecord node = new HashtableRecord();
           node.key = key; //in order to use the equals() method in HashtableNode
           LinkedList<HashtableRecord> theList = (LinkedList<HashtableRecord>) this.table[pos];
           //
           boolean removed = theList.remove(node);
           if( theList.size() == 0 )
               this.table[pos] = null;
           if( removed )
               this.numElements--;
       }
   }

   public void remove(Object [] keys) {
       for (int i = 0; i < keys.length; i++) {
           this.remove(keys[i]);
       }
   }

   public String toString() {
       String buffer = "";

       buffer += "{\n";
       for (int i = 0; i < this.table.length; i++) {
           if (this.table[i] != null) {
               buffer = buffer + "\t" + (LinkedList)this.table[i] + "\n" ;
           }
       }
       buffer += "}";
       return buffer;
   }

   public int getNumElements() {
       return this.numElements;
   }

   public boolean contains(Object key) {
       boolean result = false;
       int hash = this.hash(key);

       if (this.table[hash] != null) {
           HashtableRecord node = new HashtableRecord();
           node.key = key;
           if (((LinkedList<HashtableRecord>)this.table[hash]).indexOf(node) > -1) {
               result = true;
           }
       }
       return result;
   }
  
   public static void main(String argv[]){
       Hashtable myhash = new Hashtable();
      
       //test of strings
       System.out.println("Inital hash table is: \n" + myhash);
       myhash.put("smith", 30);
       myhash.put("john", 10);
       System.out.println("After two adds, hashtalbe is: \n" + myhash);
       myhash.put("green", 10);
       myhash.put("green", 60); //this will be added successfully, updating existing record.
       System.out.println("After four adds, hashtalbe is: \n" + myhash);
      
       myhash.remove("green");
       System.out.println("After remove green, hashtalbe is: \n" + myhash);
       /*
       System.out.println("Inital hash table is: \n" + myhash);
       myhash.put(11.5f, "smith");
       myhash.put(100.9f, "john");
       System.out.println("After two adds, hashtalbe is: \n" + myhash);
       myhash.put(3.4, "green");
       myhash.put(3.4, "white"); //this successfully updated the existing record with key = 3.4
       System.out.println("After total four adds, hashtalbe is: \n" + myhash);
      
       myhash.remove(3.4);
       System.out.println("After remove 3.4, hashtalbe is: \n" + myhash);
   */
   }

}

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


import java.util.LinkedList;
public class Hashtable {
  
   private class HashtableRecord{
       private Object key;
       private Object value;

       public HashtableRecord() {
       this.key = null;
       this.value = null;
       }

       public HashtableRecord(Object inKey, Object inData) {
       this.key = inKey;
       this.value = inData;
       }

       /* Equality can be based on key alone because there can't be
       * 2 records with the same key in the table */
       public boolean equals(Object obj) {
       if (obj instanceof HashtableRecord) {
       HashtableRecord node = (HashtableRecord)obj;
       return this.key.equals(node.key);
       }
       else {
       return false;
       }
       }
      
       public String toString() {
           return "Key: ["+this.key+"] Value: ["+this.value+"]";
           }
   }
  
   //
   //
   private final int tableSize = 101;
   private int numElements;
   private Object [] table;
     
   //constructor
   public Hashtable(int realSize) {
           this.table = new Object[realSize];
           this.numElements = 0;
   }
  
   public Hashtable() {
           this.table = new Object[this.tableSize];
           this.numElements = 0;
   }
  
   private int hash(Object key) {

       /* Start with a base, just so that it's not 0 for empty strings */
       int result = 42; //start at hard coded base
  
       String inputString = key.toString().toLowerCase();
       //System.out.println("hash string is:" + inputString + "\n");
  
       char [] characters = inputString.toCharArray();
       for (int i = 0; i < characters.length; i++) {
       char currentChar = characters[i];
       int j = (int)currentChar;
       //System.out.println("j = " + j );
       result += j;
       }
       return (result % this.table.length);
   }

   public void put(Object key, Object data) {
       if (data == null || key == null) {
       System.err.println("ERROR: Either the key or the data are null");
       return;
       }

       // If trying to add duplicate keys, that means
       // we like to update the value associated with that existing key.
       // We first delete the existing mapping, then insert a new record that key.
       if (this.contains(key)) {
       remove(key);
       }
       // Find out where in our array should the new item goes
       int pos = this.hash(key);
       // If nothing exists in the position, create a new linked list there
       if (this.table[pos] == null) {
       this.table[pos] = new LinkedList<HashtableRecord>();
       }
         
       LinkedList<HashtableRecord> theList = (LinkedList<HashtableRecord>) this.table[pos];
           // Add to the linked list in the appropriate position
           theList.add(new HashtableRecord(key, data));
           this.numElements++;
   }
     
   public void put(Object [] keys, Object [] inputData) {
       for (int i = 0; i < inputData.length; i++) {
       this.put(keys[i], inputData[i]);
       }
       }

   public Object get(Object key) {
         
       int pos = this.hash(key); // get the position in table
         
       // check if value at pos in table is not null
       if (this.table[pos] != null) {
           // create a new HashtableRecord
           HashtableRecord node = new HashtableRecord();
           node.key = key; //in order to use the equals() method in HashtableNode
           // get the LinkedList at pos
           LinkedList<HashtableRecord> theList = (LinkedList<HashtableRecord>) this.table[pos];
           // check the index of node in theList
           int index = theList.indexOf(node);
           // if index is found i.e != -1 return the value of the HashRecord at that index
           if(index != -1)
               return theList.get(index).value;
          
       }
           return null; // key not found
   }

         
       //return type is different from the standard Map interface.
       public void remove(Object key) {
       int pos = this.hash(key);

       if (this.table[pos] != null) {
       HashtableRecord node = new HashtableRecord();
       node.key = key; //in order to use the equals() method in HashtableNode
       LinkedList<HashtableRecord> theList = (LinkedList<HashtableRecord>) this.table[pos];
       //
       boolean removed = theList.remove(node);
       if( theList.size() == 0 )
       this.table[pos] = null;
       if( removed )
       this.numElements--;
       }
       }
         
       public void remove(Object [] keys) {
               for (int i = 0; i < keys.length; i++) {
               this.remove(keys[i]);
               }
       }
  
       public String toString() {
               String buffer = "";
  
               buffer += "{\n";
               for (int i = 0; i < this.table.length; i++) {
               if (this.table[i] != null) {
               buffer = buffer + "\t" + (LinkedList)this.table[i] + "\n" ;
               }
               }
               buffer += "}";
               return buffer;
       }
         
       public int getNumElements() {
           return this.numElements;
       }
         
       public boolean contains(Object key) {
           boolean result = false;
           int hash = this.hash(key);

           if (this.table[hash] != null) {
           HashtableRecord node = new HashtableRecord();
           node.key = key;
           if (((LinkedList<HashtableRecord>)this.table[hash]).indexOf(node) > -1) {
           result = true;
           }
           }
           return result;
       }
         
       public static void main(String argv[]){

           Hashtable myhash = new Hashtable();

           //test of strings
           System.out.println("Inital hash table is: \n" + myhash);
           myhash.put("smith", 30);
           myhash.put("john", 10);
           System.out.println("After two adds, hashtalbe is: \n" + myhash);
           myhash.put("green", 10);
           myhash.put("green", 60); //this will be added successfully, updating existing record.
           System.out.println("After four adds, hashtalbe is: \n" + myhash);

           myhash.remove("green");
           System.out.println("After remove green, hashtalbe is: \n" + myhash);
       /*             
           System.out.println("Inital hash table is: \n" + myhash);
           myhash.put(11.5f, "smith");
           myhash.put(100.9f, "john");
           System.out.println("After two adds, hashtalbe is: \n" + myhash);
           myhash.put(3.4, "green");
           myhash.put(3.4, "white"); //this successfully updated the existing record with key = 3.4
           System.out.println("After total four adds, hashtalbe is: \n" + myhash);

           myhash.remove(3.4);
           System.out.println("After remove 3.4, hashtalbe is: \n" + myhash);
   */         
       }
}
//end of program

Add a comment
Know the answer?
Add Answer to:
Java you are required to add a public Object get( Object key) method into the Hashtable...
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;   ...

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

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

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Currently working on a Java Assignment. I have written most codes for swap, reverse and insert....

    Currently working on a Java Assignment. I have written most codes for swap, reverse and insert. Just need a. itemCount receives a value and returns a count of the number of times this item is found in the list. c. sublist receives two indexes and returns an ArrayList of node values from the first index to the second index, provided the indexes are valid. d. select receives a variable number of indexes, and returns an ArrayList of node values corresponding...

  • Removing Nodes from a Binary Tree in Java This section requires you to complete the following...

    Removing Nodes from a Binary Tree in Java This section requires you to complete the following method within BinaryTree.java: public void remove(K key) { } The remove method should remove the key from the binary tree and modify the tree accordingly to maintain the Binary Search Tree Principle. If the key does not exist in the binary tree, no nodes should be removed. In case there is a non-null left child, it should take the place of the removed node....

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

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

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

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