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

Assume we already have a Bag Array class. The goal of this program is to write t

ID: 3836215 • Letter: A

Question

Assume we already have a Bag Array class. The goal of this program is to write the main code. You must declare two Bag Array objects of type Integer. Place some integer values in the first Bag Array object and some of the numbers maybe duplicates. After the numbers placed in the first Bag Array, transfer all the numbers from the first Bag Array to the second Bag Array without having any duplicates in the second Bag Array. Note that after this transfer, the first Bag Array should still have all the items placed in it originally.

Explanation / Answer


Given: BagArray class

Lets assume: add(int x), contains(int x), get(int z), and size() are the methods in BagArray class


so, method to transfer all contains from bag 1 to bag 2 without any duplicaticy


BagArray bag1 = new BagArray();
BagArray bag2 = new BagArray();

// putting some items in bag1
bag1.add(2);
bag1.add(1);
bag1.add(5);
bag1.add(2);
..........

bag1.add(4);
bag1.add(1);


// now transfering items from bag1 to bag2

for(int i=0; i<bag1.size(); i++){ // iterating for all items in bag1

    int x = bag1.get(i); // getting ith item from bag1

    if(! bag2.contains(x)) // checking whether x is already in bag2 or not
        bag2.add(x);
}