Question

In: Computer Science

In java the parts listed as todo in linkedsetwithlinkedbad Implement all the methods defined as skeletons...

In java the parts listed as todo in linkedsetwithlinkedbad

Implement all the methods defined as skeletons in the LinkedSetWithLinkedBag class. The class implements the SetInterface (described in Segment 1.21 of chapter 1). It utilizes LinkedBag as defined in the UML diagram below: the instance variable setOfEntries is to be an object of LinkedBag. Test your class with the test cases provided in main. Do not make any changes to provided classes other than LinkedSetWithLinkedBag.

Similar to Lab02, most of the methods can be implemented by simply calling appropriate methods from the LinkedBag, for example the clear method would be implemented as:
                public void clear()
{
    this.setOfEntries.clear();
}  
Ensure that the add method does not allow duplicates and null entries.
public class LinkedSetWithLinkedBag<T extends Comparable<? super T>> implements SetInterface<T>
{
    private LinkedBag setOfEntries;

    /**
     * Creates a set from a new, empty linked bag.
     */
    public LinkedSetWithLinkedBag()
    {
        this.setOfEntries = new LinkedBag<>();
        //TODO Project1
    } // end default constructor

    public boolean add(T newEntry)
    {

        //TODO Project1

        return false; //THIS IS A STUB
    } // end add

    public T[] toArray()
    {
        //TODO Project1
        return null; //THIS IS A STUB
    } // end toArray

    public boolean isEmpty()
    {
        //TODO Project1
        return false; //THIS IS A STUB
    } // end isEmpty

    public boolean contains(T anEntry)
    {
        //TODO Project1
        return false; //THIS IS A STUB
    } // end contains

    public void clear()
    {
        //TODO Project1
    } // end clear

    public T remove()
    {
        //TODO Project1
        return null; //THIS IS A STUB
    } // end remove

    public boolean removeElement(T anEntry)
    {
        //TODO Project1
        return false; //THIS IS A STUB
    } // end remove

    // Displays a set.
    public void displaySet()
    {
        //TODO Project1
    } // end displaySet
public class LinkedBag
{
    private Node firstNode;       // reference to first node

    public LinkedBag()
    {
        this.firstNode = null;
    } // end default constructor

    /**
     * Adds a new entry to this bag.
     *
     * @param newEntry the object to be added as a new entry
     * @return true
     */
    public boolean add(T newEntry) // OutOfMemoryError possible
    {
        // add to beginning of chain:
        Node newNode = new Node<>(newEntry);
        newNode.next = this.firstNode;  // make new node reference rest of chain
                                        // (firstNode is null if chain is empty)
        this.firstNode = newNode;       // new node is at beginning of chain

        return true;
    } // end add

    /**
     * Retrieves all entries that are in this bag.
     *
     * @return a newly allocated array of all the entries in the bag
     */
    public T[] toArray()
    {
        // the cast is safe because the new array contains null entries
        int counter = 0;
        Node currentNode = this.firstNode;
        while (currentNode != null)
        {
            counter++;
            currentNode = currentNode.next;
        }

        T[] result = (T[]) new Comparable[counter]; // unchecked cast

        int index = 0;
        currentNode = this.firstNode;
        while ((index < result.length) && (currentNode != null))
        {
            result[index] = currentNode.data;
            index++;
            currentNode = currentNode.next;
        }
        return result;
    } // end toArray

    /**
     * Sees whether this bag is empty.
     *
     * @return true if the bag is empty, or false if not
     */
    public boolean isEmpty()
    {
        return this.firstNode == null;
    } // end isEmpty

    /**
     * Gets the number of entries currently in this bag.
     *
     * @return the integer number of entries currently in the bag
     */
    public int getCurrentSize()
    {
        throw new UnsupportedOperationException();
    } // end getCurrentSize

    /**
     * Counts the number of times a given entry appears in this bag.
     *
     * @param anEntry the entry to be counted
     * @return the number of times anEntry appears in the bag
     */
    public int getFrequencyOf(T anEntry)
    {
        int frequency = 0;
        Node currentNode = this.firstNode;
        while (currentNode != null)
        {
            if (anEntry.equals(currentNode.data))
            {
                frequency++;
            }
            currentNode = currentNode.next;
        }

        return frequency;
    } // end getFrequencyOf

    /**
     * Tests whether this bag contains a given entry.
     *
     * @param anEntry the entry to locate
     * @return true if the bag contains anEntry, or false otherwise
     */
    public boolean contains(T anEntry)
    {
        return getReferenceTo(anEntry) != null;
    } // end contains

    // Locates a given entry within this bag.
    // Returns a reference to the node containing the entry, if located,
    // or null otherwise.
    private Node getReferenceTo(T anEntry)
    {
        boolean found = false;
        Node currentNode = this.firstNode;

        while (!found && (currentNode != null))
        {
            if (anEntry.equals(currentNode.data))
                found = true;
            else
                currentNode = currentNode.next;
        }

        return currentNode;
    } // end getReferenceTo

    /**
     * Removes all entries from this bag.
     */
    public void clear()
    {
        while (!isEmpty())
            remove();
    } // end clear

    /**
     * Removes one unspecified entry from this bag, if possible.
     *
     * @return either the removed entry, if the removal
     * was successful, or null
     */
    public T remove()
    {
        T result = null;
        if (this.firstNode != null)
        {
            result = this.firstNode.data;
            this.firstNode = this.firstNode.next; // remove first node from chain
        }

        return result;
    } // end remove

    /**
     * Removes one occurrence of a given entry from this bag, if possible.
     *
     * @param anElement the entry to be removed
     * @return true if the removal was successful, or false otherwise
     */
    public boolean removeElement(T anElement)
    {
        boolean result = false;
        Node nodeN = getReferenceTo(anElement);

        if (nodeN != null)
        {
            nodeN.data = this.firstNode.data; // replace located entry with entry in first node
            this.firstNode = this.firstNode.next; // remove first node from chain
            result = true;
        }

        return result;
    } // end remove


    private class Node
    {
        private S data; // entry in bag
        private Node next; // link to next node

        private Node(S dataPortion)
        {
            this(dataPortion, null);
        } // end constructor

        private Node(S dataPortion, Node nextNode)
        {
            this.data = dataPortion;
            this.next = nextNode;
        }
    } // end Node
} // end LinkedBag

Solutions

Expert Solution

Written all the functions, Make Sure you have Node and LinkedBag in your package otherwise code wont compile

public class LinkedSetWithLinkedBag<T extends Comparable<? super T>> implements SetInterface<T>

{

private LinkedBag setOfEntries;

/**

   * Creates a set from a new, empty linked bag.

   */

public LinkedSetWithLinkedBag()

{

this.setOfEntries = new LinkedBag<>();

} // end default constructor

public boolean add(T newEntry)

{

  

if(newEntry == null)

return false;

  

if(this.setOfEntries.contains(newEntry))

return false;

  

return this.setOfEntries.add(newEntry);

} // end add

public T[] toArray()

{

return this.setOfEntries.toArray();

} // end toArray

public boolean isEmpty()

{

return this.setOfEntries.isEmpty();

} // end isEmpty

public boolean contains(T anEntry)

{

return this.setOfEntries.contains(anEntry);

} // end contains

public void clear()

{

this.setOfEntries.clear();

} // end clear

public T remove()

{

return this.setOfEntries.remove();

} // end remove

public boolean removeElement(T anEntry)

{

return this.setOfEntries.removeElement(anEntry);

} // end remove

// Displays a set.

public void displaySet()

{

Node currentNode = this.setOfEntries.firstNode;

while (currentNode != null)

{

System.out.print(currentNode.data + " ");

currentNode = currentNode.next;

}

  

} // end displaySet

}

Thanks, PLEASE COMMENT if there is any concern.


Related Solutions

Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import java.util.List; /** * An abstraction over the idea of a search. * * @author liberato * * @param <T> : generic type. */ public abstract class Searcher<T> { protected final SearchProblem<T> searchProblem; protected final List<T> visited; protected List<T> solution; /**    * Instantiates a searcher.    *    * @param searchProblem    *            the search problem for which this searcher will find and   ...
In Java For this assignment you will implement two methods, find() and replace() relating to Binary...
In Java For this assignment you will implement two methods, find() and replace() relating to Binary Search Trees. These methods are both to be recursive functions. The signatures for those functions must be: /* This method takes a tree node and a key as an argument and returns the tree node if the key is found and returns null if the key is not found. */ BST find(BST T, char key) /* This method takes a tree node and a...
Implement the following methods in Java: a. A method named MergeFileswith the following signature that gets...
Implement the following methods in Java: a. A method named MergeFileswith the following signature that gets two file names and write the content of the first file (sourceFile) into the beginning of the second file (destinationFile. For example, if sourceFile contains “Hello ” and destinationFile contains “World!”, this method must keep sourceFile as it is, but replace the content of the second file by “Hello World!”.public static voidMergeFiles(String sourceFile, String destinationFile) b. A recursive method with the following signature that...
IN JAVA: Implement an algorithm to check whether a LinkedList is a palindrome. 2 methods should...
IN JAVA: Implement an algorithm to check whether a LinkedList is a palindrome. 2 methods should be implemented: Constant space, i.e. without creating extra copies of the linked list Unrestricted space q1: / For this implementation you should use constant space   // Note: you are free to add any extra methods,   // but this method has to be used   public static boolean isPalindromeRestricted(ListNode head) {     // Your code goes here     return false;   } q2: // For this implementation the space...
JAVA the task is to implement the missing methods in the LinkedIntSet class. Each method you...
JAVA the task is to implement the missing methods in the LinkedIntSet class. Each method you must write has comments describing how it should behave. You may not add any new fields to the LinkedIntSet class and you may only add new code inside the bodies of the 5 methods you are asked to write. You may also write new private helper methods. However, you may not change any method headers, you may not change any code outside of the...
IN JAVA. I have the following code (please also implement the Tester to test the methods...
IN JAVA. I have the following code (please also implement the Tester to test the methods ) And I need to add a method called public int remove() that should remove the first integer of the array and return it at the dame time saving the first integer and bring down all other elements. After it should decrease the size of the array, and after return and save the integer. package ourVector; import java.util.Scanner; public class ourVector { private int[]...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not loops. You may use JDK String methods like substring() and length(), but do not use the JDK methods to avoid coding the algorithms assigned. For example, don't use String.reverse(). public boolean recursiveContains(char c, String s) returns true if the String contains the char, otherwise returns false. Here is the code for this method, which you should use as an example to see how to...
Program in java 1- Implement an algorithms to calculate the sum of all numbers in an...
Program in java 1- Implement an algorithms to calculate the sum of all numbers in an array.   2- Implement an algorithm to determine if an array has all unique integer values. 3- Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Code in Java Create a stack class to store integers and implement following methods: 1) void...
Code in Java Create a stack class to store integers and implement following methods: 1) void push(int num): This method will push an integer to the top of the stack. 2) int pop(): This method will return the value stored in the top of the stack. If the stack is empty this method will return -1. 3) void display(): This method will display all numbers in the stack from top to bottom (First item displayed will be the top value)....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT