Question

JAVA

Submit:    HashSet.java    with the following methods added:

B.longestLinkedList an int method that returns the number of nodes in the longest linked list of this HashSet. The empty set

B. longestLinkedList(); The HashSet Class from our textbook uses chained hashing, and this method will return the length of t

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 given element to this set, if it was not already

// contained in the set.

//Method toString2()
public String toString2() {

String output = "";
String index = "";
String data[][] = new String[elementData.length][elementData.length];
int temp = 0;

if (!isEmpty()) {
  
   for (int i = 0; i < elementData.length; i++){
   for (int j = 0; j < elementData.length; j++) {
   data[i][j] = "";
   }
   }
     
   for (int i = 0; i < elementData.length; i++) {
   int j = 0;
   HashEntry <E> current = elementData[i];
   index += String.format("[" + i + "]");
     
   while (current != null) {
   data[i][j++] += current.data;
   current = current.next;
   }
     
   if (temp < j)
   temp = j;
   index += "\t";
   }

   index += "\n";
   output += index;

   for (int i = 0; i < temp; i++) {
   for (int j = 0; j < elementData.length; j++) {

   if (!data[j][i].equals(""))
   output += data[j][i];

   else
   output += " ";
   output += "\t";
   }
   output += "\n";
   }
   }
   return output;
   }

public void add(E 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<E>(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(E value) {

int bucket = hashFunction(value);

HashEntry<E> current = elementData[bucket];

while (current != null) {

if (current.data.equals(value)) {

return true;

}

current = current.next;

}

return false;

}

// Returns true if there are no elements.

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(E value) {

int bucket = hashFunction(value);

if (elementData[bucket] != null) {

// check front of list

if (elementData[bucket].data.equals(value)) {

elementData[bucket] = elementData[bucket].next;

size--;

} else {

// check rest of list

HashEntry<E> current = elementData[bucket];

while (current.next != null && !current.next.data.equals(value)) {

current = current.next;

}

// if the element is found, remove it

if (current.next != null && current.next.data.equals(value)) {

current.next = current.next.next;

size--;

}

}

}

}

// Returns the number of elements.

public int size() {

return size;

}

// Returns a string representation 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<E> 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(E value) {

return Math.abs(value.hashCode()) % elementData.length;

}

private double loadFactor() {

return (double) size / elementData.length;

}

// Resizes the hash table to twice its former size.

@SuppressWarnings("unchecked")

private void rehash() {

// replace element data array with a larger empty version

HashEntry<E>[] 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<E> current = oldElementData[i];

while (current != null) {

add((E)current.data);

current = current.next;

}

}

}

// Represents a single value in a chain stored in one hash bucket.

@SuppressWarnings("hiding")

private class HashEntry<E> {

public E data;

public HashEntry<E> next;

@SuppressWarnings("unused")

public HashEntry(E data) {

this(data, null);

}

public HashEntry(E data, HashEntry<E> next) {

this.data = data;

this.next = next;

}

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
        public int longestLinkedList() {
                int longest = 0;
                for (int i = 0; i < elementData.length; i++) {
                        
                        int count = 0;
                        HashEntry<E> start = elementData[i];
                        
                        while(start != null) {
                                count++;
                                start = start.next;
                        }
                        
                        if(count > longest) {
                                longest = count;
                        }
                        
                }
                
                return longest;
                
        }

If you have any issues, please ask in comments.. Please do not unnecessarily downvote the answer directly like you did last time.. Ask your questions in comment, and i will help surely.

Add a comment
Know the answer?
Add Answer to:
JAVA Submit:    HashSet.java    with the following methods added: HashSet.java // Implements a set of...
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
  • 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...

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

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

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

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

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

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

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

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

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

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