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

Java Question Write an intersection method for the ResizableArrayBag class. The

ID: 3666478 • Letter: J

Question

Java Question

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> intersecion(ResizableArrayBag <T> anotherBag)

Example:

bag1 contains (1, 2, 2, 3)

bag2 contains (2, 2, 2, 4, 5)

then bag1.intersection(bag2) would return a new bag that contains (2, 2)

The contents of bag1 and bag2 would be the same.

(The order of the intersection bag might not match the above, since bags are unordered.)

Explanation / Answer

public BagInterface<T> intersecion(ResizableArrayBag<T> anotherBag){
      
       ResizableArrayBag intersectionBag = new ResizableArrayBag();
       ResizableArrayBag bag1 = this; // getting caller bag
      
       HashMap<Integer,Integer> map = new HashMap<>();
       int i=0;
       while(i < bag1.size()){ // putting bag1 elements in map with count value
           if(map.containsKey(bag1.get(i))){
               map.put(bag1.get(i), map.get(bag1.get(i))+1); // increasing count of existing number
           }else{
               map.put(bag1.get(i), 1);
           }
       }
      
       for(i=0; i<anotherBag.size(); i++) {// checking each element of anotherBag in map(for match)
           if(map.containsKey(anotherBag.get(i))){
               if(map.get(anotherBag.get(i)) > 0){ // if count is greater than one, means current element is present in both bag
                   intersectionBag.add(anotherBag.get(i));
                   map.put(anotherBag.get(i), map.get(anotherBag.get(i))-1); // decreasing count
               }
           }
       }
      
       return intersectionBag;
      
   }

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