Question: It is a coding problem with Java, This Project is about array and an abstract class Bag. The capacity of it is fixed, and we
It is a coding problem with Java, This Project is about array and an abstract class Bag. The capacity of it is fixed, and we need to put the new items into it. If the current number of items larger than the capacity, for example, the capacity is 5, and the current array is [1,2,3,4,5], we want to put new item 6. The array should change to [2,3,4,5,6]. I complete the toString part.
However, my insert part print nothing.
Here are the constructor and field part. I wrote the toString method.


So, there is maybe something wrong with it.
And I am confused about the union method.

Can anyone help me with it?
\
![5, and the current array is [1,2,3,4,5], we want to put new](https://dsd5zvtm8ll6.cloudfront.net/si.experts.images/questions/2024/09/66f9058f241eb_91866f9058ebd2aa.jpg)
Here is the test code.
Here is the detailed information:
![item 6. The array should change to [2,3,4,5,6]. I complete the toString](https://dsd5zvtm8ll6.cloudfront.net/si.experts.images/questions/2024/09/66f9058faea27_91966f9058f5041c.jpg)

And the main method.
Code in copy and paste:
import java.util.Iterator;
public class Bag
private int capacity;
private E[] items;
private int n; // number of elements in bag
/**
*
* @param capacity Fixed size bag capacity
*/
public Bag(int capacity){
this.capacity = capacity;
this.items = (E[])new Object[capacity];
}
@Override
public String toString() {
String str= "";
for(int i = 0; i
if(i == n - 1) {
str += items[i];
}else {
str += items[i];
str += ",";
}
}
return str;
}
public void insert(E item) {
// TODO Auto-generated method stub
E[] cur = (E[])new Object[capacity];
for(int i = 0; i
cur[i] = item;
}
if (n == capacity) {
for( int i = 1; i
cur[i - 1] = item;
}
for(int i = 0; i
cur[i] = items[i];
}
}
for(int i = 0; i
items[i] = item;
}
}
@Override
public void union(LoopBag
// TODO Auto-generated method stub
}
package loopbag;
import static org.junit.Assert.assertEquals;
import java.util.Iterator;
/**
Main
*/
public class Main {
public static void main(String[] args) {
LoopBag
LoopBag
for(int i = 1; i
bag.insert(i);
}
System.out.println(bag);
bag2.insert(5);
bag2.insert(6);
bag2.insert(7);
bag2.insert(8);
bag2.insert(1);
bag.union(bag2);
System.out.println(bag);
}
}
/TEST CODE/
public void testUnion1(){
LoopBag
LoopBag
bag1.insert(1);
bag1.insert(2);
bag2.insert(1);
bag2.insert(2);
bag1.union(bag2);
String answer="1,2";
assertEquals(answer, bag1.toString());
}
3 import java.util.Iterator; 4 5 public class Bag
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
