I am confused about my current project. It is about the array. The capacity of i
ID: 3909276 • Letter: I
Question
I am confused about my current project. It is about the array. 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.
The insert part does not work somehow.
Here is the test code for this insert method.
And another test.
3 import java.util.Iterator; 4 5 public class Bag implements LoopBag 6 7 the capacity of bag private int capacity, private EL 1tems; private int n; // number of elements in bag 10 12e 13 14 15 16e 17 18 19 20 21 22e 23 24 25 26 27 28 29 30 31 32 *@param capacity Fixed size bag capacity public Bag(int capacity)i this.capacitycapacity; this. items = CEDnew 0bject [capacity]'; @Override public String toStringO String str- ""; for(int i - 0; iExplanation / Answer
The Insert function here is not working because:
Line Number 47 : We have to insert item to cur[] instead of items[] simply because we are creating a new array cur which stores the shifted values.
Also we have to use cur[n -1] = item because we have to insert item to the last element of the array instead of n as index starts from 0.
we have to write a loop once again to store values back into items[] because it is the member variable of the class not cur[].
public void insert(E item)
{
E[] cur = (E[])new Object[capacity];
if(n == capacity)
{
for( int i = 1; i < capacity; i++ )
{
cur[i - 1] = items[i];
}
}
cur[n-1] = item;
for(int i = 0;i<capacity;i++)
{
items[i] = cur[i];
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.