In: Computer Science
Could i get a walk trough how to solve these questions. Note that is where the answer is meant to go.
Question 1
Say, instead of a separate variable (nItems), the number of items currently in the list are stored at index 0 in the array data, the actual values being stored starting at index 1. Complete the constructor that instantiates a list that can hold n values (excluding the item that holds the number of items currently in the list). That is, one should be able to add n values to the list before the need to grow it.
public class PackedArrayList {
public int[] data;
public PackedArrayList(int n) {
data = new int[ ];
data[0] = ;
}
}
Question 2
Complete the body of method addEnsureCapacity in the following
code:
public class MyArrayList {
public int[] data;
public int nItems;
public MyArrayList(int n) {
data = new int[n];
nItems = 0;
}
public void grow() {
//assume it increases capacity by 10
}
public boolean isFull() {
return (nItems == data.length);
}
public void addBasic(int val) {
data[nItems] = val;
nItems++;
}
public void addEnsureCapacity(int val) {
if( == false) {
;
}
else {
;
addBasic(val);
}
}
}
Q1) Solution:
public class PackedArrayList {
public int[] data;
public PackedArrayList(int n) {
data = new int[ n+1 ]; //it should be n+1 as we are storing n
value at index 0 and we want n values to store.
data[0] = 0 ; //as we are initializing the array this willl be
0 and should be adjusted with values in array.
}
}
Q2) Solution:
public class MyArrayList {
public int[] data;
public int nItems;
public MyArrayList(int n) {
data = new int[n];
nItems = 0;
}
public void grow() {
//assume it increases capacity by 10
}
public boolean isFull() {
return (nItems == data.length);
}
public void addBasic(int val) {
data[nItems] = val;
nItems++;
}
public void addEnsureCapacity(int val) {
if( isFull() == false) { //if isFull() returns false then we
have space in array to store more
addBasic(val); //as isFull() is false we can call addBasic to
store the val.
}
else {
grow(); //we reach else if isFull() returns true which means
there is no more space left in array so we call grow()
addBasic(val);
}
}
}
If you find this helpful. Please upvote the answer and if
you have any doubts please leave a comment.