Java Exception Handling The class IntList as defined below stores a list of inte
ID: 3701297 • Letter: J
Question
Java Exception Handling
The class IntList as defined below stores a list of integers using an inter- nal array. Implement the method void remove(int i) so that it removes ith element from the list. The list must shift the elements from the right of the internal array by one slot when ith element is removed and update length field. If the parameter i is out of bound, it must throw an instance of Exception with appropriate error messsage.
Do you need to modify the declaration of remove method for throwing this exception?
length++;
b[i] = a[i]; }
a = b; }
// TODO }
}
Explanation / Answer
class IntList {
private int[] a; // internal array to store integers
private int length = 0; // size of the list
IntList() { a = new int[10]; } // initial size of the array is 10
// add integer x to the list and double array size as necessary
void add(int x) {
length++;
if(length > a.length) {
int[] b = new int[a.length * 2];
for(int i=0; i<a.length; i++) {
b[i] = a[i]; }
a = b; }
a[length-1] = x;
}
// remove ith element from the list and compact the list afterwards
// throw exception if i is illegal
void remove(int i) throws Exception {
if(i>a.length){
throw new Exception("i is out of the array length");
}
int[] b = new int[a.length -1]; //create a temporary array to store the array list without the element at i
for(int j=0;j<i-1;j++){
b[j]=a[j];
}
for(int j=i;j<a.length;j++){
b[j-1]=a[j];
}
a=b;
length--;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.