Question: In an array-based Seq implementation, a friend wrote the following code for an insert method: 116 public void insert(CarControl element) 117 { 118 ensureCapacity(2*contents.length+1); 119
In an array-based Seq implementation, a friend wrote the following code for an insert method:
116 public void insert(CarControl element) 117 { 118 ensureCapacity(2*contents.length+1); 119 120 ++manyItems; 121 122 if (currentIndex == manyItems) { 123 contents[currentIndex] = element; 124 } else if (currentIndex == 0) { 125 for (int i=manyItems; i > 0; --i) { 126 contents[i] = contents[i-1]; 127 } 128 } else { 129 for (int i=currentIndex; i < manyItems; ++i) { 130 contents[i+1] = contents[i]; 131 } 132 } 133 134 contents[currentIndex] = element; 135 136 }
- As soon as you see the code, without even looking at the actual details of the logic, you can see that it is likely to have bugs. Why? Explain!
- There is a JUnit test suite that has lots of tests that stops after the first error. When you run the code with the JUnit test suite, the result is:
java.lang.ArrayIndexOutOfBoundsException: 1 at edu.uwm.cs351.DiskSeq.insert(DiskSeq.java:126) at Driver.testDiskSeq(Driver.java:182) at Driver.main(Driver.java:27) Initial tests Passed 112 tests. Failed 1 test.
Why would 1 be a bad array index in the given code? Surely the array has at least one element? - You fix a problem on line 125, and now the code passes all tests. But there are still two errors. The first was not found by the test suite because it never tested inserting an element before the second element of a sequence with at least three elements. What is the bug?
- Why does the test suite not detect the problem even though it inserts at all locations in a two element sequence (at the start, in the middle and at the end?)
- There is another problem which happens when one inserts 28 elements in the sequence. It gets slower and slower and then there is an OutOfMemoryError. What is this error? Why did the test suite not catch it?
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
