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

Problem: implement the method and constructor with added requirements addAll( )

ID: 3784213 • Letter: P

Question

Problem: implement the method and constructor with added requirements

addAll( ) : adjust the type of the parameter, it is an ArrayBag with the same generic type parameter; the method checks if the parameter bag is null or the array field of the parameter is empty, in either case send a message “Nothing was added to the bag” to the console and return the method; otherwise, use the code deemed as wrong implementation on page 142: find a small modification to avoid the trap of an infinite loop as we discussed in class. Do not use the arraycopy method!

Here is my code so far...having issues with dealing with the inifinte loop, for example suppose we have a bag 'b' and activate it with b.addAll(b). Then the private instance variable 'manyItems' is the same as addend.manyItems. Each iteration of the loop adds 1 to manyItems; so addend.manyItems is also increasing making an infinite loop

public void addAll(ArrayBag addend)
{

if (addend == null){
throw new IllegalArgumentException("The bag is empty.");
}
else{
int i;

ensureCapacity(manyItems + addend.manyItems);
for (i = 0; i < addend.manyItems; i++){
add(addend.data[i]);
}
}

code of ensure capacity method...probably irrelevant, but just to be sure...

public void ensureCapacity(int cap)
{
if(cap <= data.length)
return;
T[] longer = (T[]) new Object[cap];
System.arraycopy(data, 0, longer, 0, manyItems);
data = longer;
  
}

Explanation / Answer

Hi Friend, Please find my implementation.

Please let me know in case of any issue.

public void addAll(ArrayBag<T> addend)

   {

       if (addend == null){

           throw new IllegalArgumentException("The bag is empty.");

       }

       else{

           // starting index in data

           int k = manyItems;

           ensureCapacity(manyItems + addend.manyItems);

           for (int i = 0; i < addend.manyItems; i++){

               data[k++] = addend.getArrElement(i);

           }

           // updating value of manyItems

           manyItems = manyItems + addend.manyItems;

       }

   }

   public void ensureCapacity(int cap)

   {

       if(cap < data.length)

           return;

       T[] longer = (T[]) new Object[cap];

       System.arraycopy(data, 0, longer, 0, manyItems);

       data = longer;

   }

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