Question

Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project...

Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project inside the ArraySetWithArray class. As shown in the UML diagram below ArraySetWithArray class does not utilize ResizableArrayBag object as its instance variable, it has setOfEntries defined as an array which should be dynamically resized if more room needed (double the size). displaySet method should check if the set is empty and display appropriate message; if the set is not empty should display the number of elements and the capacity, followed by all the elements in the set (see sample run). Test your class with the test cases provided in main. See the sample run below.
public class ArraySetWithArray<T extends Comparable<? super T>> implements SetInterface<T>
{
    private T[] setOfEntries;
    private int numberOfEntries;
    private boolean initialized = false;
    private static final int DEFAULT_CAPACITY = 3; // Initial capacity of array
    private static final int MAX_CAPACITY = 10000;

    /**
     * Creates an empty array whose initial capacity is 3.
     */
    public ArraySetWithArray()
    {
        //TODO Project2
    } // end default constructor

    /**
     * Creates an empty array having a given initial capacity.
     *
     * @param capacity The integer capacity desired.
     */
    public ArraySetWithArray(int capacity)
    {
        //TODO Project2
    } // end constructor

    /**
     * Creates an array containing given entries.
     *
     * @param contents An array of objects.
     */
    public ArraySetWithArray(T[] contents)
    {
        //TODO Project2
    } // end constructor

    /**
     * Throws an exception if the client requests a capacity that is too large.
     */
    private void checkCapacity(int capacity)
    {
        if (capacity > MAX_CAPACITY)
            throw new IllegalStateException("Attempt to create a bag whose capacity exceeds " +
                    "allowed maximum of " + MAX_CAPACITY);
    } // end checkCapacity

    /**
     * Throws an exception if receiving object is not initialized.
     */
    private void checkInitialization()
    {
        if (!this.initialized)
            throw new SecurityException("Uninitialized object used " +
                    "to call an ArrayBag method.");
    } // end checkInitialization

    /**
     * Adds a new entry to this array, avoiding duplicates.
     *
     * @param newEntry The object to be added as a new entry.
     * @return True if the addition is successful, or false if not.
     */
    public boolean add(T newEntry)
    {
        //TODO Project2
        return false; //THIS IS A STUB
    } // end add

    /**
     * Checks if the set is full; if it is full doubles its size
     */
    private void ensureCapacity()
    {
        //TODO Project2
    } // end ensureCapacity

    /**
     * Retrieves all entries that are in this array.
     *
     * @return A newly allocated array of all the entries.
     */
    public T[] toArray()
    {
        //TODO Project2
        return null; //THIS IS A STUB
    } // end toArray

    /**
     * Sees whether this array is empty.
     *
     * @return True if this array is empty, or false if not.
     */
    public boolean isEmpty()
    {
        //TODO Project2
        return false;
    } // end isEmpty

    /**
     * Gets the number of entries currently in this array.
     *
     * @return The integer number of entries currently in the array.
     */
    public int getCurrentSize()
    {
        //TODO Project2
        return 0; //THIS IS A STUB
    } // end getCurrentSize

    /**
     * Tests whether this array contains a given entry.
     *
     * @param anEntry The entry to locate.
     * @return True if the array contains anEntry, or false if not.
     */
    public boolean contains(T anEntry)
    {
        //TODO Project2

        // utilize getIndexOf method
        return false; //THIS IS A STUB
    } // end contains

    /**
     * Locates a given entry within the array bag.
     * Returns the index of the entry, if located,
     * or -1 otherwise.
     * Precondition: checkInitialization has been called.
     */
    private int getIndexOf(T anEntry)
    {
        int where = -1;
        // TODO Project 2

        return where;
    } // end getIndexOf

    /**
     * Removes all entries from this array.
     */
    public void clear()
    {
        //TODO Project2
    } // end clear

    /**
     * Removes one unspecified entry from this bag.
     *
     * @return Either the removed entry if the removal
     * was successful, or null if not.
     */
    public T remove()
    {
        //TODO Project2
        return null; //THIS IS A STUB
    } // end remove

    /**
     * Removes one occurrence of a given entry from this array.
     *
     * @param anEntry The entry to be removed.
     * @return True if the removal was successful, or null if not.
     */
    public boolean removeElement(T anEntry)
    {
        //TODO Project2
        return false;
    } // end removeElement

    // Removes and returns the array entry at a given index.
    // If no such entry exists, returns null.
    private T removeEntry(int givenIndex)
    {
        //TODO Project2
        return null; //THIS IS A STUB
    } // end removeEntry

    // Displays a set.
    // If the set is empty displays a message that the set is empty and display the capacity
    // if the set is not empty displays the number of elements, capacity and the content of the set
    public void displaySet()
    {
        //TODO Project2
    } // end displaySet
0 0
Add a comment Improve this question Transcribed image text
Answer #1
public class ArraySetWithArray<T extends Comparable<? super T>>
{
    private T[] setOfEntries;
    private int numberOfEntries;
    private boolean initialized = false;
    private static final int DEFAULT_CAPACITY = 3; // Initial capacity of array
    private static final int MAX_CAPACITY = 10000;

    /**
     * Creates an empty array whose initial capacity is 3.
     */
    public ArraySetWithArray()
    {
        this(DEFAULT_CAPACITY);
    } // end default constructor

    /**
     * Creates an empty array having a given initial capacity.
     *
     * @param capacity The integer capacity desired.
     */
    @SuppressWarnings("unchecked")
    public ArraySetWithArray(int capacity)
    {
        this.setOfEntries = (T[]) new Object[capacity];
        this.numberOfEntries = 0;
        initialized = true;
    } // end constructor

    /**
     * Creates an array containing given entries.
     *
     * @param contents An array of objects.
     */
    @SuppressWarnings("unchecked")
    public ArraySetWithArray(T[] contents)
    {
        this.setOfEntries = (T[]) new Object[contents.length];
        for(int i=0; i<contents.length; i++) {
            setOfEntries[i] = contents[i];
        }
        this.numberOfEntries = 0;
        initialized = true;
    } // end constructor

    /**
     * Throws an exception if the client requests a capacity that is too large.
     */
    private void checkCapacity(int capacity)
    {
        if (capacity > MAX_CAPACITY)
            throw new IllegalStateException("Attempt to create a bag whose capacity exceeds " +
                    "allowed maximum of " + MAX_CAPACITY);
    } // end checkCapacity

    /**
     * Throws an exception if receiving object is not initialized.
     */
    private void checkInitialization()
    {
        if (!this.initialized)
            throw new SecurityException("Uninitialized object used " +
                    "to call an ArrayBag method.");
    } // end checkInitialization

    /**
     * Adds a new entry to this array, avoiding duplicates.
     *
     * @param newEntry The object to be added as a new entry.
     * @return True if the addition is successful, or false if not.
     */
    public boolean add(T newEntry)
    {
        if(contains(newEntry))
            return false;

        ensureCapacity();
        setOfEntries[numberOfEntries++] = newEntry;
        return true;
    } // end add

    /**
     * Checks if the set is full; if it is full doubles its size
     */
    @SuppressWarnings("unchecked")
    private void ensureCapacity()
    {
        if(numberOfEntries == setOfEntries.length) {
            checkCapacity(numberOfEntries * 2);
            // Must increase capacity: double in size
            T b[] = (T[]) new Object[2 * numberOfEntries];
            for (int i = 0; i < numberOfEntries; i++) {
                b[i] = setOfEntries[i];
            }
            this.setOfEntries = b;
        }
    } // end ensureCapacity

    /**
     * Retrieves all entries that are in this array.
     *
     * @return A newly allocated array of all the entries.
     */
    @SuppressWarnings("unchecked")
    public T[] toArray()
    {
        T b[] = (T[]) new Object[numberOfEntries];
        for (int i = 0; i < numberOfEntries; i++) {
            b[i] = setOfEntries[i];
        }

        return b;
    } // end toArray

    /**
     * Sees whether this array is empty.
     *
     * @return True if this array is empty, or false if not.
     */
    public boolean isEmpty()
    {
        return numberOfEntries == 0;
    } // end isEmpty

    /**
     * Gets the number of entries currently in this array.
     *
     * @return The integer number of entries currently in the array.
     */
    public int getCurrentSize()
    {
        return numberOfEntries;
    } // end getCurrentSize

    /**
     * Tests whether this array contains a given entry.
     *
     * @param anEntry The entry to locate.
     * @return True if the array contains anEntry, or false if not.
     */
    public boolean contains(T anEntry)
    {
        return getIndexOf(anEntry) != -1; //THIS IS A STUB
    } // end contains

    /**
     * Locates a given entry within the array bag.
     * Returns the index of the entry, if located,
     * or -1 otherwise.
     * Precondition: checkInitialization has been called.
     */
    private int getIndexOf(T anEntry)
    {
        for (int i = 0; i < numberOfEntries; i++) {
            if(setOfEntries[i].equals(anEntry)) {
                return i;
            }
        }

        return -1;
    } // end getIndexOf

    /**
     * Removes all entries from this array.
     */
    public void clear()
    {
        numberOfEntries = 0;
    } // end clear

    /**
     * Removes one unspecified entry from this bag.
     *
     * @return Either the removed entry if the removal
     * was successful, or null if not.
     */
    public T remove()
    {
        if(numberOfEntries > 0) {
            return setOfEntries[--numberOfEntries];
        }
        return null;
    } // end remove

    /**
     * Removes one occurrence of a given entry from this array.
     *
     * @param anEntry The entry to be removed.
     * @return True if the removal was successful, or null if not.
     */
    public boolean removeElement(T anEntry)
    {
        int index = getIndexOf(anEntry);
        if(removeEntry(index) != null) {
            return true;
        }
        return false;
    } // end removeElement

    // Removes and returns the array entry at a given index.
    // If no such entry exists, returns null.
    private T removeEntry(int givenIndex)
    {
        if(givenIndex >= 0 && givenIndex < numberOfEntries) {
            T x = setOfEntries[givenIndex];
            setOfEntries[givenIndex] = setOfEntries[--numberOfEntries];
            return x;
        }
        return null;
    } // end removeEntry

    // Displays a set.
    // If the set is empty displays a message that the set is empty and display the capacity
    // if the set is not empty displays the number of elements, capacity and the content of the set
    public void displaySet()
    {
        StringBuffer sb = new StringBuffer();
        if (numberOfEntries == 0) {
            sb.append("Set is empty\n");
        } else {
            sb.append("Set contains " + numberOfEntries + " elements.\n");
        }
        sb.append("Set capacity: " + setOfEntries.length + " elements.\n");

        sb.append("[");
        for (int i = 0; i < numberOfEntries-1; i++) {
            sb.append(setOfEntries[i].toString());
            sb.append(", ");
        }
        sb.append(setOfEntries[numberOfEntries - 1]);
        sb.append("]");
        System.out.println(sb.toString());
    } // end displaySet
}


Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project...
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 Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • Suppose that you have several numbered billiard balls on a pool table. The smallest possible number...

    Suppose that you have several numbered billiard balls on a pool table. The smallest possible number on the ball is “1”. At each step, you remove a billiard ball from the table. If the ball removed is numbered n, you replace it with n balls randomly numbered less than n. For example, if you remove the “5” ball, you replace it with balls numbered “2”, “1”, “1”, “4”, and “3”, where numbers 2, 1, 1, 4, and 3 were randomly...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the...

    Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the first item containing a given value from a doubly linked list. The header of the method is as follows: public boolean removeValue(T aValue) where T is the general type of the objects in the list and the methods returns true if such an item is found and deleted. Include testing of the method in a main method of the DoublyLList class. ------------------------------------------------------------------------------------- /** A...

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

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • import java.util.*; /** * A class that implements the ADT set by using a linked bag....

    import java.util.*; /** * A class that implements the ADT set by using a linked bag. * The set is never full. * * */ public class LinkedSetWithLinkedBag> implements SetInterface { private LinkedBag setOfEntries; /** * Creates a set from a new, empty linked bag. */ public LinkedSetWithLinkedBag() { //TODO Project1 } // end default constructor public boolean add(T newEntry) { //TODO Project1 // new node is at beginning of chain if(this.setOfEntries.isEmpty()) { if (!this.setOfEntries.contains(newEntry)) this.setOfEntries.add(newEntry); } return true; //...

  • c++ Please create Set.cpp and Set.h The following information is needed (setinterface.h) Class Set You are...

    c++ Please create Set.cpp and Set.h The following information is needed (setinterface.h) Class Set You are given an interface: SetInterfac This is a public interface and completely specifies what the Set class operations must be. SetInterface is an abstract class (it has no implementation), so your Set class must inherit from SetInterface and implement all of its methods. Set differs in the fact that it does not allow duplicates. This also means that add()must check that an element is not...

  • 5. Below i s the class deciaration for the Bag class from your text. Refer to...

    5. Below i s the class deciaration for the Bag class from your text. Refer to this hea he Ted implementation @file Bag.h #ifndet BAG #define BAG template <class ItemType> class Bag private: static const int DEFAULT BAG SIZE 6; Il current count of Bag items /I max capacity of the Bag ItemType items[DEFAULT BAG SIZE]; //array of Bag items int itemCount; int maxitems; /l Returns either the index of the element in the array items that ll contains the...

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