Question

Assignment: A set is a collection of items without repetitions. The goal of this assignment is...

Assignment: A set is a collection of items without repetitions. The goal of this assignment is to implement a set as a data structure. Do the following.

1. (30 points) Starting with the template attached, implement a generic class Set(T) that maintains a set of items of generic type T using the class ArrayList(T) in the Java API. Your Set class must provide the following instance methods:

add: that adds a new item. (Ignore if already in the set.)

remove: that removes an item. (Ignore if not in the set.)

membership: that returns true if a given item is in the set and false otherwise.

toString: that returns a string with the list of the items in the set.

2. (30 points) Write a testSet class with a main() method that tests all the operations of the Set class above. That is, create an empty set A of integers, obtain from the user some integers and store some in A, display the set using toString(), obtain from the user some integers and remove them from A using remove(), display the set using toString(), obtain an integer from the user and check whether it is in A or not using membership() and display the result.

---

import java.util.*;

public class Set<T>{
    //data fields
    private ArrayList<T> myList;
    
    // constructors
    Set(){
        // CODE HERE
    }
    // other methods
    public void add(T item){
        // CODE HERE
    }
    public void remove(T item){
        // CODE HERE
    }
    public Boolean membership(T item){
        // CODE HERE
    }
    public String toString(){
        // CODE HERE
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Set.java

import java.util.ArrayList;

public class Set<T> {

       //data fields

    private ArrayList<T> myList;

   

    // constructors

    Set(){

       myList = new ArrayList<T>();

    }

    // other methods

    public void add(T item){

       if(!membership(item))

             myList.add(item);

    }

    public void remove(T item){

       if(membership(item))

             myList.remove(item);

      

    }

    public Boolean membership(T item){

       for(int i=0;i<myList.size();i++)

             if(myList.get(i).equals(item))

                    return true;

       return false;

    }

    public String toString(){

       String str = "[ ";

       for(int i=0;i<myList.size()-1;i++)

       {

             str += myList.get(i).toString()+", ";

       }

      

       if(myList.size() > 0)

       {

             str += myList.get(myList.size()-1).toString();

       }

      

       str += " ]";

      

       return str;

    }

}

//end of Set.java

// TestSet.java

import java.util.Scanner;

public class TestSet {

       public static void main(String[] args) {

             // create an empty set A of integers

             Set<Integer> A = new Set<Integer>();

             Scanner scan = new Scanner(System.in);

             int num;

             System.out.println("Enter 10 integers to insert : ");

            

             // obtain from the user some integers and store some in A

             for(int i=0;i<10;i++)

             {

                    System.out.print("Enter integer-"+(i+1)+" : ");

                    num = scan.nextInt();

                    A.add(num);

             }

             //display the set using toString()

             System.out.println("Set : "+A);

            

             //obtain from the user some integers and remove them from A using remove()

             System.out.println("Enter 5 integers to remove : ");

             for(int i=0;i<5;i++)

             {

                    System.out.print("Enter integer-"+(i+1)+" : ");

                    num = scan.nextInt();

                    A.remove(num);

             }

            

             // display the set using toString()

             System.out.println("Set : "+A);

            

             // obtain an integer from the user

             System.out.print("Enter the integer to check if it is present in Set or not : ");

             num = scan.nextInt();

            

             // check whether it is in A or not using membership() and display the result.

             if(A.membership(num))

                    System.out.println(num+" is present in Set A");

             else

                    System.out.println(num+" is not present in Set A");

            

             scan.close();

       }

}

//end of TestSet.java

Output:

Add a comment
Know the answer?
Add Answer to:
Assignment: A set is a collection of items without repetitions. The goal of this assignment is...
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
  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • CSBP 319 Data structures - Linked Lists - USE JAVA (NetBeans) A company would like to...

    CSBP 319 Data structures - Linked Lists - USE JAVA (NetBeans) A company would like to implement its inventory of computing machines as a linked list, called ComputerList. Write a Computer node class, called ComputerNode, to hold the following information about a Computer: • code (as a String) • brand (as a String) • model (as a String) • price (as double) • quantity (as int) ComputerNode should have constructors and methods (getters, setters, and toString()) to manage the above...

  • 10.3 Example. When you first declare a new list, it is empty and its length is...

    10.3 Example. When you first declare a new list, it is empty and its length is zero. If you add three objects—a, b, and c—one at a time and in the order given, to the end of the list, the list will appear as a b c The object a is first, at position 1, b is at position 2, and c is last at position 3.1 To save space here, we will sometimes write a list’s contents on one...

  • 02. Second Assignment – The FacebookUser Class We’re going to make a small change to the...

    02. Second Assignment – The FacebookUser Class We’re going to make a small change to the UserAccount class from the last assignment by adding a new method: public abstract void getPasswordHelp(); This method is abstract because different types of user accounts may provide different types of help, such as providing a password hint that was entered by the user when the account was created or initiating a process to reset the password. Next we will create a subclass of UserAccount...

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

  • The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write...

    The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write code to show how the JCF class ArrayList and LinkedList are used to maintain a grocery list. Verify List methods such as "add()", get(), "remove()", "isEmpty()" and "size()" by implementing a test program. import java.util.ArrayList; import java.util.Iterator; public class GroceryList { static public void main(String[] args){ ArrayList<String> groceryList = new ArrayList<String>(); Iterator<String> iter;    groceryList.add("apples"); groceryList.add("bread"); groceryList.add("juice"); groceryList.add("carrots"); groceryList.add("ice cream");    System.out.println("Number of items...

  • The purpose of this is to use inheritance, polymorphism, object comparison, sorting, reading binary files, and...

    The purpose of this is to use inheritance, polymorphism, object comparison, sorting, reading binary files, and writing binary files. In this application you will modify a previous project. The previous project created a hierarchy of classes modeling a company that produces and sells parts. Some of the parts were purchased and resold. These were modeled by the PurchasedPart class. Some of the parts were manufactured and sold. These were modeled by the ManufacturedPart class. In this you will add a...

  • Java programming The purpose of this problem is to practice using a generic Urn class. NOTE:...

    Java programming The purpose of this problem is to practice using a generic Urn class. NOTE: Refer to the code for the ArrayStack class from Chapter 12. Use that code as a starting point to create the Urn class, modifying it to remove the methods in the ArrayStack class (push, pop, etc) then add the methods described below. Also change the variable names to reflect the new class. For example the array name should NOT be stack, instead it should...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).

    Ch 7 Program: Online shopping cart (continued) (Java)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt)Public member methodssetDescription() mutator & getDescription() accessor (2 pts)printItemCost() - Outputs the item name followed by the quantity, price, and subtotalprintItemDescription() - Outputs 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