Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2) .(10 points) Write a generic class called Bag. It should have three methods a

ID: 3721566 • Letter: 2

Question

2) .(10 points) Write a generic class called Bag. It should have three methods as follows: The add method should take in two generic values and save them into the theoretical bag, returning nothing from the method. The contains method should take the second type of generic parameter, and return whether or not that value is located in the theoretical bag. The isEmpty method should take no parameters and return true if the bag is empty, and false otherwise. For example, the class should support the following behavior:

Bag<Integer,Integer> bag1 = new Bag<Integer,Integer>();

Bag<Integer,String> bag2 = new Bag<Integer,String>();

Bag<String,Double> bag3 = new Bag<String,Double>();     

bag1.add( 20, 92 );

bag2.add( 20, “A-” );

bag3.add( “B", 84.5 );

// prints false

System.out.printf( “Bag 1 is empty? %s ”, bag1.isEmpty() );

// prints false

System.out.printf( “Found B in bag 2? %s ”, bag2.contains(“B”) );

// prints true

System.out.printf( “Found 84.5 in bag 3? %s ”, bag3.contains(84.5) );

Explanation / Answer

import java.util.HashMap;

public class Bag<T,E> {

   private HashMap<T,E> map;

  

   public Bag() {

       map = new HashMap<>();

   }

  

   public void add(T t, E e) {

       map.put(t, e);

   }

  

   public boolean isEmpty() {

       return map.size() == 0;

   }

  

   public boolean contains(E item) {

       for(T key : map.keySet()) {

           if(map.get(key) == item)

               return true;

       }

       return false;

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote