Question

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 returns true if your set contains every element from the other set. For example, if the set stores [-2, 3, 5, 6, 8] and the method is passed [3, 6, 8], your method would return true. If the method were passed [3, 6, 7, 8], your method would return false because your set does not contain the value 7. Write a method in the HashIntSet class called equals that accepts another object as a parameter and returns true if the object is another HashIntSet that contains exactly the same elements. The internal hash table size and ordering of the elements does not matter, only the sets of elements themselves. Please also create a Main program to test the code. Provided Files ****************** HashIntSet.java ****************** // Implements a set of integers using a hash table. // The hash table uses separate chaining to resolve collisions. 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 set, if it was not already // contained in the set. public void add(int value) { if (!contains(value)) { if (loadFactor() >= MAX_LOAD_FACTOR) { rehash(); } // insert new value at front of list int bucket = hashFunction(value); elementData[bucket] = new HashEntry(value, elementData[bucket]); size++; } } // Removes all elements from the set. public void clear() { for (int i = 0; i < elementData.length; i++) { elementData[i] = null; } size = 0; } // Returns true if the given value is found in this set. public boolean contains(int value) { int bucket = hashFunction(value); HashEntry current = elementData[bucket]; while (current != null) { if (current.data == value) { return true; } current = current.next; } return false; } // Returns true if there are no elements in this queue. public boolean isEmpty() { return size == 0; } // Removes the given value if it is contained in the set. // If the set does not contain the value, has no effect. public void remove(int value) { int bucket = hashFunction(value); if (elementData[bucket] != null) { // check front of list if (elementData[bucket].data == value) { elementData[bucket] = elementData[bucket].next; size--; } else { // check rest of list HashEntry current = elementData[bucket]; while (current.next != null && current.next.data != value) { current = current.next; } // if the element is found, remove it if (current.next != null && current.next.data == value) { current.next = current.next.next; size--; } } } } // Returns the number of elements in the queue. public int size() { return size; } // Returns a string representation of this queue, such as "[10, 20, 30]"; // The elements are not guaranteed to be listed in sorted order. public String toString() { String result = "["; boolean first = true; if (!isEmpty()) { for (int i = 0; i < elementData.length; i++) { HashEntry current = elementData[i]; while (current != null) { if (!first) { result += ", "; } result += current.data; first = false; current = current.next; } } } return result + "]"; } // Returns the preferred hash bucket index for the given value. private int hashFunction(int value) { return Math.abs(value) % elementData.length; } private double loadFactor() { return (double) size / elementData.length; } // Resizes the hash table to twice its former size. private void rehash() { // replace element data array with a larger empty version HashEntry[] oldElementData = elementData; elementData = new HashEntry[2 * oldElementData.length]; size = 0; // re-add all of the old data into the new array for (int i = 0; i < oldElementData.length; i++) { HashEntry current = oldElementData[i]; while (current != null) { add(current.data); current = current.next; } } } // Represents a single value in a chain stored in one hash bucket. private class HashEntry { public int data; public HashEntry next; public HashEntry(int data) { this(data, null); } public HashEntry(int data, HashEntry next) { this.data = data; this.next = next; } } }

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  1. public void addAll(HashIntSet set) : This method accepts another hash set as a parameter and adds all of the elements from the this set into the current set.
    • Here we loop through all the elements inside the parameter set and get each HashEntry.
    • Using While Loop we loop to all HashEntry object inside given set
    • We check if its not null, then we add the data of this HashEntry in the current set object.
    • Then move to next HashEntry
    • Here we are using existing add(int value) function to add each data of given set to the existing set inside loop

   // Method accepts another hash set as a parameter and adds all of the elements from the this set into the current set.
   public void addAll(HashIntSet set)
   {
       for (int i = 0; i < set.elementData.length; i++)
       {
           HashEntry current = set.elementData[i];
           while (current != null)
           {
               this.add(current.data);
              
               current = current.next;
           }
       }
   }

========================================================================================

2. public boolean containsAll(HashIntSet set) : Method accepts another hash set as a parameter and returns true if your set contains every element from the other set.

  • We check if the current is empty by calling isEmpty() method. If it returns true then we return false for contains all method.
  • We loop through all the elements inside the parameter set and get each HashEntry.
  • Using While Loop we loop to all HashEntry object inside given set
  • We check if its not null, then we call contains(int value) methos to check if data of this HashEntry is present in the current set object.
  • If any single data is not present in current object set then directly return false else set the result flag as true for each present value and return that result flag at the end.
  • Then move to next HashEntry.

// Method accepts another hash set as a parameter and returns true if your set contains every element from the other set.
   public boolean containsAll(HashIntSet set)
   {
       boolean result = false;
       if (!isEmpty())
       {
           for (int i = 0; i < set.elementData.length; i++)
           {
               HashEntry current = set.elementData[i];
               while (current != null)
               {
                   if(this.contains(current.data))
                   {
                       result = true;
                   }
                   else
                   {
                       return false;
                   }
                   current = current.next;
               }
           }
       }
       return result;
   }

============================================================================================

3.    public boolean equals(HashIntSet set) : Method that accepts another object as a parameter and returns true if the object is another HashIntSet that contains exactly the same elements.

  • We check if the size of given set and the current set is equal by calling existing size() function.
  • If size is not equal then directly return false.
  • If size if not equal then check if current set contains the entire given set by calling containsAll(HashIntSet set) created by us previously.
  • Return the result returned by containsAll(..) method which will be true if all data is present else false.

   // Method that accepts another object as a parameter and returns true if the object is another HashIntSet that contains exactly the same elements.
   public boolean equals(HashIntSet set)
   {
       boolean result = false;
       if (this.size() == set.size())
       {
           result = this.containsAll(set);
       }
      
       return result;
   }

===========================================================================================

Please find the entire HashIntSet.java file below:-

//Implements a set of integers using a hash table.
// The hash table uses separate chaining to resolve collisions.
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 set, if it was not already
   // contained in the set.
   public void add(int value)
   { if (!contains(value))
       {
           if (loadFactor() >= MAX_LOAD_FACTOR)
           {
               rehash();
           }
           // insert new value at front of list
           int bucket = hashFunction(value);
           elementData[bucket] = new HashEntry(value, elementData[bucket]);
           size++;
       }
   }
  
   // Method accepts another hash set as a parameter and adds all of the elements from the this set into the current set.
   public void addAll(HashIntSet set)
   {
       for (int i = 0; i < set.elementData.length; i++)
       {
           HashEntry current = set.elementData[i];
           while (current != null)
           {
               this.add(current.data);
              
               current = current.next;
           }
       }
   }
  
   // Removes all elements from the set.
   public void clear()
   {
       for (int i = 0; i < elementData.length; i++)
       {
           elementData[i] = null;
       } size = 0;
   }
  
   // Returns true if the given value is found in this set.
   public boolean contains(int value)
   {
       int bucket = hashFunction(value);
       HashEntry current = elementData[bucket];
       while (current != null)
       {
           if (current.data == value)
           {
               return true;
           }
           current = current.next;
       } return false;
   }
  
   // Method accepts another hash set as a parameter and returns true if your set contains every element from the other set.
   public boolean containsAll(HashIntSet set)
   {
       boolean result = false;
       if (!isEmpty())
       {
           for (int i = 0; i < set.elementData.length; i++)
           {
               HashEntry current = set.elementData[i];
               while (current != null)
               {
                   if(this.contains(current.data))
                   {
                       result = true;
                   }
                   else
                   {
                       return false;
                   }
                   current = current.next;
               }
           }
       }
      
       return result;
   }
  
   // Method that accepts another object as a parameter and returns true if the object is another HashIntSet that contains exactly the same elements.
   public boolean equals(HashIntSet set)
   {
       boolean result = false;
       if (this.size() == set.size())
       {
           result = this.containsAll(set);
       }
      
       return result;
   }
  
   // Returns true if there are no elements in this queue.
   public boolean isEmpty()
   {
       return size == 0;
   }
  
   // Removes the given value if it is contained in the set.
   // If the set does not contain the value, has no effect.
   public void remove(int value)
   {
       int bucket = hashFunction(value);
       if (elementData[bucket] != null)
       {
           // check front of list
           if (elementData[bucket].data == value)
           {
               elementData[bucket] = elementData[bucket].next; size--;
           }
           }
           else
           {
               // check rest of list
               HashEntry current = elementData[bucket];
               while (current.next != null && current.next.data != value)
               {
                   current = current.next;
               }
               // if the element is found, remove it
               if (current.next != null && current.next.data == value)
               {
                   current.next = current.next.next; size--;
               }
           }
       }

   // Returns the number of elements in the queue.
   public int size()
   {
       return size;
   }
  
   // Returns a string representation of this queue, such as "[10, 20, 30]";
   // The elements are not guaranteed to be listed in sorted order.
   public String toString()
   {
       String result = "[";
       boolean first = true;
       if (!isEmpty())
       {
           for (int i = 0; i < elementData.length; i++)
           {
               HashEntry current = elementData[i];
               while (current != null)
               {
                   if (!first)
                   {
                       result += ", ";
                   }
                   result += current.data;
                   first = false;
                   current = current.next;
               }
           }
       }
      
       return result + "]";
   }
  
   // Returns the preferred hash bucket index for the given value.
   private int hashFunction(int value)
   {
       return Math.abs(value) % elementData.length;
   }
  
   private double loadFactor()
   {
       return (double) size / elementData.length;
   }
  
   // Resizes the hash table to twice its former size.
   private void rehash()
   {
       // replace element data array with a larger empty version
       HashEntry[] oldElementData = elementData;
       elementData = new HashEntry[2 * oldElementData.length]; size = 0;
       // re-add all of the old data into the new array
       for (int i = 0; i < oldElementData.length; i++)
       {
           HashEntry current = oldElementData[i];
           while (current != null)
           {
               add(current.data); current = current.next;
           }
       }
   }
  
   // Represents a single value in a chain stored in one hash bucket.
   private class HashEntry
   {
       public int data;
       public HashEntry next;
      
       public HashEntry(int data)
       {
           this(data, null);
       }
      
       public HashEntry(int data, HashEntry next)
       {
           this.data = data;
           this.next = next;
       }
   }
}

-----------------------------------------------------------------------------------------------------------------------------------

Main.java file to test the sets:-

public class Main
{
   public static void main(String[] args)
   {
       HashIntSet set1 = new HashIntSet();
       set1.add(1);
       set1.add(2);
       set1.add(2);
       set1.add(3);
       set1.add(3);
       set1.add(4);
       System.out.println("HashSet ==> "+set1.toString());

       HashIntSet set2 = new HashIntSet();
       set2.add(3);
       set2.add(4);
       set2.add(5);
       set2.add(5);
       System.out.println("set1 Contains set2 ? ==> "+set1.containsAll(set2));
      
       set1.addAll(set2);
      
       System.out.println("HashSet after addAll ==> "+set1.toString());
       System.out.println("set1 Contains set2 after addind set2 in set1 ==> "+set1.containsAll(set2));
       System.out.println("set1 Equals set1 ? ==> "+set1.equals(set1));
       System.out.println("set1 Equals set2 ? ==> "+set1.equals(set2));
   }
}

Please find the result of above testing below:-

eclipse-workspace - Test/src/test/Main.java - Eclipse Eile Edit Source Refactor Navigate Search Project Run Window Help & ION

Add a comment
Know the answer?
Add Answer to:
Write a method in the HashIntSet class called addAll that accepts another hash set as a...
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
  • 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...

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

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

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

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

  • 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 help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Doubly Linked List Java Help Details: First, read the DoublyLinkedList.java code and try to under...

    Doubly Linked List Java Help Details: First, read the DoublyLinkedList.java code and try to understand what each field stores and what each method is doing. Modify and complete the class as described below •The field size was defined in the class but was never maintained. Set the current default value and modify it whenever it is needed in the existing methods and other methods you implement as it is needed. It should always include the number of Nodes inside the...

  • Add a method to the DoubleLinkedList class built in class to reverse every set of values...

    Add a method to the DoubleLinkedList class built in class to reverse every set of values For example: 1, 2, 3, 4, 5, 6 Reverse 3: 3,2,1,6,5,4 Reverse 2: 2,1,4,3,6,5 Reverse 6: 6,5,4,3,2,1 Method header: public void reverseSegments(int setSize) outcome should be like this: Input:​​​​​​​​​​​​​​ 3 1 2 3 4 5 6 output: 3 2 1 6 5 4 Input:​​​​​​​​​​​​​​​​​​​​​ 2 ​​​​​​​1 2 3 4 5 6 output: 2 1 6 5 4 3 ============================================code====================================================================== public class MyDoubleLinkedList<E> { private...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

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