minor problem and short amount of code. I have below an incorrect code for an ad
ID: 3621367 • Letter: M
Question
minor problem and short amount of code. I have below an incorrect code for an add method. This method is supposed to1.) create another array that is one unit larger than the existing one
2.) copy all of the elements from the existing array over to the new one
3.) add the parameter to the end of the new array
4.) re-assign the instance variable "values" so that it refers to the new array
My code is incomplete, but here is what I have (keep in mind that variable values is defined at top of the class by public int[] values;).
public void add(int number) {
int [] list = new int[number+1];
for (int ind = 0; ind < number-1; ind++){
list[ind] = values[ind];
}
list[number+1]=number;
}
Explanation / Answer
This is a very bad code. What happens if you pass 10 as number and the highest bound of your array values[] is 5. Big out of bound error and it also definitely will not add 1 to the existing array. public void add(int number) { int [] list = new int[values.length + 1]; for (int ind = 0; indRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.