Question

Complete the following case study: Case study: Three implementations of contains - comparing approaches to adding...

Complete the following case study:

Case study: Three implementations of contains - comparing approaches to adding functionality

Set A contains Set B if every element in Set B is also in Set A. We will compare three ways to determine whether Set A contains Set B.

Approach 1: Write code in the main method in a test class

Add code to the main of ArraySetTester to create SetA and SetB, fill them with data and write a contains operation that tests if SetA contains SetB.

Question: What is wrong with this approach?
Answer: While the code does the operation for the specific collections SetA and SetB, it only applies to these two collections. The code can't be used for other Sets without repeating it.

Approach 2: Write a static method in a test class

Comment out the code from approach 1.

Add a static method to ArraySetTester with prototype:

   public static boolean contains(SetADT<Integer> Set1, SetADT<Integer> Set2)

Question: Why does contains need to be static?
Answer: We aren't instantiating an object to call the contains. Therefore contains has to be associated with the ArraySetTester class itself, rather than a particular instance.

Question: Why were Set1 and Set2 declared as SetADT rather than as ArraySet?
Answer: This way the contains method can be called for any implementation of SetADT.

Approach 3: Add a prototype to the interface

Add the following prototype to the SetADT interface and add an implementation of contains to ArraySet.

   public boolean contains(SetADT<T> Set)

Question: Why is Approach 3 generally better than Approach 2?
Answer: We have associated the code for contains with the classes that need it most, i.e., if you call contains, you will need SetADT and an implementation of it. This is the object-oriented approach. We can ask the object itself whether it contains another.

ArraySet.java

package arraysetpackage;

import java.util.Iterator;

public class ArraySetTester {


   public static void main(String[] args) {
       SetADT <String> mySet = new ArraySet<String>();

       for (int i = 0; i < 12; i++)
           mySet.add(new String("apple"+i));

       System.out.println(mySet);
      
       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
       mySet.add(new String ("apple0"));
       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
       System.out.println("contains 11? = "+mySet.contains(new String("11")));
       System.out.println("contains apple11? = "+mySet.contains(new String("apple11")));      
      
       try {
           String removedItem = mySet.remove("apple7");
           System.out.println(mySet);
           System.out.println(removedItem+ " was removed");
       } catch (Exception e) {
           System.out.println("item not found, can't remove");
       }
      
       try {
           String removedItem = mySet.remove("apple17");
           System.out.println(mySet);
           System.out.println(removedItem+ " was removed");
       } catch (Exception e) {
           System.out.println("item not found, can't remove");
       }
      
       Iterator<String> iter = mySet.iterator();
       while (iter.hasNext()){
           System.out.println(iter.next());
       }

ArraySetIterator.java

package arraysetpackage;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArraySetIterator <T> implements Iterator <T> {
   private int position; //Always points to the next value
   private T [] values;
   private int count;
  
  
   public ArraySetIterator (T [] theValues, int aCount) {
       position = 0;
       values = theValues;
       count = aCount;
   }
  
   public boolean hasNext() {
       return position < count;
   }
  
   public T next() {
       if (position >= count)
           throw new NoSuchElementException("Past " + count + " elements");
       position++;
       return values[position - 1];
    }
  
   public void remove() {
       throw new
       UnsupportedOperationException("No remove for ArraySet");
   }

}

ArraySetTester.java

package arraysetpackage;

import java.util.Iterator;

public class ArraySetTester {


   public static void main(String[] args) {
       SetADT <String> mySet = new ArraySet<String>();

       for (int i = 0; i < 12; i++)
           mySet.add(new String("apple"+i));

       System.out.println(mySet);
      
       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
       mySet.add(new String ("apple0"));
       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
       System.out.println("contains 11? = "+mySet.contains(new String("11")));
       System.out.println("contains apple11? = "+mySet.contains(new String("apple11")));      
      
       try {
           String removedItem = mySet.remove("apple7");
           System.out.println(mySet);
           System.out.println(removedItem+ " was removed");
       } catch (Exception e) {
           System.out.println("item not found, can't remove");
       }
      
       try {
           String removedItem = mySet.remove("apple17");
           System.out.println(mySet);
           System.out.println(removedItem+ " was removed");
       } catch (Exception e) {
           System.out.println("item not found, can't remove");
       }
      
       Iterator<String> iter = mySet.iterator();
       while (iter.hasNext()){
           System.out.println(iter.next());
       }

       SetADT <String> mySet2 = new ArraySet<String>();

       for (int i = 0; i < 12; i++)
           mySet2.add(new String("orange"+i));  
       System.out.println(mySet2);
      
       // add code here to test methods you finish in ArraySet
      
      
      
       // after you complete the existing methods, do the Case Study
       // Approach 1 will be here in the main
      
      
      
       // Approach 2 will be here in ArraySetTester, but you will
       // create a local static method that you will call from the main
      
       // Approach 3 will start with uncommenting the prototype in SetADT
       // and then creating the method in ArraySet. Finally you will write
       // code here to test the new method
      
   }


}

SetADT.java

package arraysetpackage;

import java.util.Iterator;

public interface SetADT<T> {
       public void add (T element); //Adds one element to this set, ignoring duplicates
       public void addAll (SetADT<T> set); //Adds all elements in the parameter to this set,
                                           // ignoring duplicates
       public T removeRandom (); //Removes and returns a random element from this set
       public T remove (T element); //Removes and returns the specified element from this set
       public SetADT<T> union (SetADT<T> set); //Returns the union of this set and the
                                               // parameter
       public boolean contains (T target); //Returns true if this set contains the parameter
       //public boolean contains(SetADT<T> Set); // Returns true if this set contains the parameter
       public boolean equals (SetADT<T> set); //Returns true if this set and the parameter
                                              //contain exactly same elements
       public boolean isEmpty(); //Returns true if this set contains no elements
       public int size(); //Returns the number of elements in this set
       public Iterator<T> iterator(); //Returns an iterator for the elements in this set
       public String toString(); //Returns a string representation of this set
}

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

import java.util.Iterator;

public class ArraySetTester {


    public static void main(String[] args) {
        SetADT <String> mySet = new ArraySet<String>();
        SetADT <String> oSet = new ArraySet<String>();
        SetADT <Integer> intSet1 = new ArraySet<Integer>();
        SetADT <Integer> intSet2 = new ArraySet<Integer>();

        for (int i = 0; i < 12; i++)
        {
            mySet.add(new String("apple"+i));
            oSet.add(new String("apple"+i + 1));
            intSet1.add(new Integer(i));
            intSet2.add(new Integer(i));
        }

        System.out.println(mySet.equals(oSet));
        System.out.println(intSet1.equals(intSet2));
        System.out.println(mySet.removeRandom());
        System.out.println(mySet.equals(oSet));
        System.out.println(mySet.union(oSet));


//   Start of provided code---------------------------------------------
//       System.out.println(mySet);
//
//       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
//       mySet.add(new String ("apple0"));
//       System.out.println("mysize = "+mySet.size()+ " [expect 12]");
//       System.out.println("contains 11? = "+mySet.contains(new String("11")));
//       System.out.println("contains apple11? = "+mySet.contains(new String("apple11")));
//
//       try {
//           String removedItem = mySet.remove("apple7");
//           System.out.println(mySet);
//           System.out.println(removedItem+ " was removed");
//       } catch (Exception e) {
//           System.out.println("item not found, can't remove");
//       }
//
//       try {
//           String removedItem = mySet.remove("apple17");
//           System.out.println(mySet);
//           System.out.println(removedItem+ " was removed");
//       } catch (Exception e) {
//           System.out.println("item not found, can't remove");
//       }
//
//       Iterator<String> iter = mySet.iterator();
//       while (iter.hasNext()){
//           System.out.println(iter.next());
//       }
//
//
//
//       SetADT <String> mySet2 = new ArraySet<String>();
//
//       for (int i = 0; i < 12; i++)
//           mySet2.add(new String("orange"+i));
//       System.out.println(mySet2);
//
        // add code here to test methods you finish in ArraySet
//   End of provided code---------------------------------------------------


        // after you complete the existing methods, do the Case Study
        //Case 1
//       SetADT <String> setA = new ArraySet<String>();
//       SetADT <String> setB = new ArraySet<String>();
//       boolean found = true;
//       boolean next = false;
//
//       for (int i = 0; i < 12; i++)
//       {
//           setA.add(new String("apple"+i));
//           if (i % 2 == 0)
//           {
//               setB.add(new String("apple"+i));
//           }
//       }
//
//       Iterator<String> iterB = setB.iterator();
//
//       while(iterB.hasNext())
//       {
//           String temp = iterB.next();
//           Iterator<String> iterA = setA.iterator();
//           while(iterA.hasNext())
//           {
//               if (temp.equals(iterA.next()))
//               {
//                   next = true;
//                   break;
//               }
//           }
//           if (!next)
//           {
//               found = false;
//               break;
//           }
//       }
//       if (!found)
//       {
//           System.out.println("Set A does not contain Set B.");
//       }
//       else
//       {
//           System.out.println("Set A contains Set B.");
//       }


        // Approach 2 will be here in ArraySetTester, but you will
//       SetADT <Integer> setA = new ArraySet<Integer>();
//       SetADT <Integer> setB = new ArraySet<Integer>();
//
//       for (int i = 0; i < 12; i++)
//       {
//           setA.add(i);
//           if (i % 2 == 0)
//           {
//               setB.add(i);
//           }
//       }
//
//       System.out.println(contains(setA, setB));

        // Approach 3 will start with uncommenting the prototype in SetADT
        // and then creating the method in ArraySet. Finally you will write
        // code here to test the new method
        SetADT <String> setA = new ArraySet<String>();
        SetADT <String> setB = new ArraySet<String>();
        boolean found = true;
        boolean next = false;

        for (int i = 0; i < 12; i++)
        {
            setA.add(new String("apple"+i));
            if (i % 2 == 0)
            {
                setB.add(new String("apple"+i));
            }
        }
        System.out.println(setA.contains(setB));
    }

//public static boolean contains(SetADT<Integer> set1, SetADT<Integer> set2)
//{
//   Iterator<Integer> iter = set2.iterator();
//
//   while (iter.hasNext())
//   {
//       if (!set1.contains(iter.next()))
//       {
//           return false;
//       }
//   }
//
//   return true;
//}

}
-------------------------------------------------------------------------------------------------------------
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;

public class ArraySet<T> implements SetADT<T> {
    private static final int DEFAULT_SIZE = 20;
    private int count;
    private T[] setValues;
    private Random rand;

    public ArraySet (){
        this(DEFAULT_SIZE);
    } // end of constructor

    public ArraySet (int size){
        count = 0;
        setValues = (T[]) new Object[size];
        rand = new Random();
    } // end of constructor


    public void add(T element) {
        if (contains(element))
            return;
        if (count == setValues.length) {
            T[] temp = (T[]) new Object[setValues.length*2];
            for (int i = 0; i < setValues.length; i++) {
                temp[i] = setValues[i];
            }
            setValues = temp;
        }
        setValues[count] = element;
        count++;
    }

    public void addAll(SetADT<T> set)
    {
        Iterator<T> iter = set.iterator();
        while (iter.hasNext())
        {
            add(iter.next());
        }

    }

    public boolean contains(T target) {
        for (int i = 0; i < count; i++ )
            if (setValues[i].equals(target))
                return true;
        return false;
    }

    public boolean contains(SetADT<T> set)
    {
        Iterator<T> iter = set.iterator();
        boolean found = false;
        T temp;

        while (iter.hasNext())
        {
            temp = iter.next();
            for (int i = 0; i < count; i++)
            {
                if (setValues[i].equals(temp))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                return false;
            }
        }

        return true;
    }

    public String toString () {
        String toReturn = "[";
        for (int i = 0; i < count; i++) {
            toReturn += setValues[i] + " ";
        }
        toReturn +="]";
        return toReturn;
    }

    public boolean equals(SetADT<T> set)
    {
        Iterator<T> iter = set.iterator();
        T temp;
        for (int i = 0; i < count; i++)
        {
            if (!iter.hasNext())
            {
                return false;
            }
            temp = iter.next();
            if (!setValues[i].equals(temp))
            {
                return false;
            }
        }
        if (iter.hasNext())
        {
            return false;
        }
        return true;
    }

    public boolean isEmpty() {
        return count==0;
    }

    public Iterator<T> iterator() {
        return new ArraySetIterator<T>(setValues,count);
    }

    public T remove(T element) {
        for (int i = 0; i < count; i++ ) {
            if (setValues[i].equals(element)) {
                T toReturn = setValues[i];
                setValues[i] = setValues[count-1];
                count--;
                return toReturn;
            }
        }
        throw new NoSuchElementException("not present");
    }


    public T removeRandom()
    {
        rand = new Random();
        int index = rand.nextInt(count);
        T tempVal = setValues[index];
        T[] tempArr = (T[]) new Object[count - 1];
        for (int i = 0; i < index; i++)
        {
            if (i != index)
            {
                tempArr[i] = setValues[i];
            }
        }
        for (int i = index; i < (count - 1); i++)
        {
            tempArr[i] = setValues[i + 1];
        }
        setValues = tempArr;
        count--;
        return tempVal;
    }

    public int size() {
        return count;
    }

    public SetADT<T> union(SetADT<T> set)
    {
        SetADT<T> toReturn = new ArraySet<T>(this.count);
        Iterator<T> iter = set.iterator();
        Iterator<T> thisIter = this.iterator();
        while (thisIter.hasNext())
        {
            toReturn.add(thisIter.next());
        }
        while (iter.hasNext())
        {
            toReturn.add(iter.next());
        }
        return toReturn;
    }

}
----------------------------------------------------------------------------------------------------------------------
import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArraySetIterator <T> implements Iterator <T> {
    private int position; //Always points to the next value
    private T [] values;
    private int count;


    public ArraySetIterator (T [] theValues, int aCount) {
        position = 0;
        values = theValues;
        count = aCount;
    }

    public boolean hasNext() {
        return position < count;
    }

    public T next() {
        if (position >= count)
            throw new NoSuchElementException("Past " + count + " elements");
        position++;
        return values[position - 1];
    }

    public void remove() {
        throw new
                UnsupportedOperationException("No remove for ArraySet");
    }

}

-----------------------------------------------------------------------------------------------------------
import java.util.Iterator;

public interface SetADT<T> {
    public void add (T element);
    public void addAll (SetADT<T> set);
    public T removeRandom ();
    public T remove (T element);
    public SetADT<T> union (SetADT<T> set);
    public boolean contains (T target);
    public boolean contains(SetADT<T> set);
    //public boolean contains(SetADT<T> Set);
    public boolean equals (SetADT<T> set);
    //contain exactly same elements
    public boolean isEmpty();
    public int size();
    public Iterator<T> iterator();
    public String toString();
}



ArraySetTester ldeaProjects/ArraySetTester] - .src/ArraySetTester.java [ArraySetTester] ArraySetTestersrc ArraySetTester 3 ~ldeaProjects/ArraySetTester Project ArraySetTester java x SetADTjava ArraySetiterator java ArraySet.java x import java.util.Iterator ArraySetTester トー.idea ▼ public class ArraySetTester f src public static void main(String[] args) ArraySet ArraySetiterator ArraySetTester SetADT SetADT <Strings mySet new ArraySet String for (int = 0; 흐 < 12; 1++) 10 nySet.add(new String original: apple +i)); . ArraySetTester.iml System.out.print In(myset); 12 13 14 15 16 17 18 19 20 lI External Libraries Scratches and Consoles Systen. out . print un(mesįzg=mySet . size()+ [expect 121); nySet.add (ew String.( orignal: applea)); System.out.printun(mysǐ鷸=-mySet.size()+ [expect 12); System.out.print ln(contains 117+mySet.containsew String original: 11)); System.out.println(contains apple11?mySet.contains (new String original: apple11))) try ArraySetTester main) Run: to /Library/Java/JavaVirtualMachines/jdk-9.อ.4. jdk/Contents/Home/bin/java -javaagent/Applications/Inteuǐנ IDEA 2018.3 EAP. app/Contents/lib/ idea rt.jar-61507: /Applications/Intelli) İDEA 2018 lapplee applel apple2 apple3 apple4 apple5 apple6 apple7 apple8 apple9 apple18 apple11 1 mysize- 12 [expect 12] mysize = 12 [expect 12] contains 117 = false contains apple117 = true apple apple1 apple2 apple3 apple4 apple5 apple6 apple11 apple8 apple9 apple18 1 apple7 was removed item not found, cant renove applea applel appled apple3 apple4 apple5 apple6 apple11 apple8 apple9 apple10 orangea orangel orange2 orange3 orange4 orange5 orange6 orange7 orange8 orange9 orange10 orangell ] Process finished with exit code 8 Q Event Log Terminal Messages 4: Run T000 Compilation completed successfully in 4 s 415 ms (a minute ago

Add a comment
Know the answer?
Add Answer to:
Complete the following case study: Case study: Three implementations of contains - comparing approaches to adding...
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
  • Methods enforced by the set interface: import java.util.Iterator; public interface Set<E> { /** Removes all of...

    Methods enforced by the set interface: import java.util.Iterator; public interface Set<E> { /** Removes all of the elements from this set */ void clear(); /** Returns true if this set contains no elements @return true if this set contains no elements */ boolean isEmpty(); /** Returns the number of elements in this set (its cardinality) @return the number of elements in this set */ int size(); /** Returns an iterator over the elements in this set @return an iterator over...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • Create a linked list with given code Given code: import java.util.Iterator; public interface Set { /**...

    Create a linked list with given code Given code: import java.util.Iterator; public interface Set { /** Removes all of the elements from this set */ void clear(); /** Returns true if this set contains no elements @return true if this set contains no elements */ boolean isEmpty(); /** Returns the number of elements in this set (its cardinality) @return the number of elements in this set */ int size(); /** Returns an iterator over the elements in this set @return...

  • In Java You may add any classes or methods to the following as you see fit in order to complete t...

    In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

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

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

  • create a class named IntegerQueue given a singlylinkedqueue of integers, write the following methods: max(SinglyLinkedQueue<Integer> s)...

    create a class named IntegerQueue given a singlylinkedqueue of integers, write the following methods: max(SinglyLinkedQueue<Integer> s) to return the max element in the queu. min(SinglyLinkedQueue<Integer> s) to return the min element in the queue. sum(SinglyLInkedQueue<Integer> s) to return the sum of elements in the queu. median(SinglyLinkedQueue<Integer> s) to return the median of elements in the queue. split(SinglyLinkedQueue<Integer> s) to separate the SinglyLinkedQueue into two ArrayQueues based on whether the element values are even or odd. package Stack_and_Queue; import java.util.Iterator; import...

  • NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT...

    NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT WOULD CAUSE THE HW1.java TO PRINT THE RIGHT DATA.!!! The LinkedList class implements both the List interface and the Stack interface, but several methods (listed below) are missing bodies. Write the code so it works correctly. You should submit one file, LinkedList.java. Do not change the interfaces. Do not change the public method headers. Do not rename the LinkedList class. None of your methods...

  • PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY....

    PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY. THE CODE IS IN JAVA PROGRAMMING LANGUAGE. import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; import java.lang.RuntimeException; import java.util.Arrays; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess {    protected Object[] data; protected int size; public int size() {     return size; }    private void rangeCheck(int index) {     if (index < 0 || index >= size) throw new IndexOutOfBoundsException(""); }    @SuppressWarnings("unchecked") private 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