Supposing you are writing your own ArrayList data structure with the following d
ID: 3793684 • Letter: S
Question
Supposing you are writing your own ArrayList data structure with the following declaration and partial code. Complete the code by an add (declaration given below) function making sure that if the ArrayList is already full, you double is. Assume that you have a size() function that will return an int value which is the total amount of element you have in that ArrayList at a given time. ****Given below ar two constructors that you may need in your add function. public class ArrayList {objects [] a/public ArrayList (int n) {a = new object [n], for (int i = o, iExplanation / Answer
Solution:
Since no declaration of add() is provided so it was assumed that add() will take the element to be added as parameter. Here a check is provided presumming size() provides the int value of the number of elements in the ArrayList as mentioned above. If the check is a success the array is copied with the new size (sort of reinitialized) where we use Arrays.copyOf(arg1, arg2) method which takes two arguments: arg1 is the original array to be copied and arg2 is the current length to be set in the new array. Since anyways the element is to be added to the array so the adding of the element is kept out of the conditional check
public void add (Object o){
int currentLength = a.length;
if(size() >= currentLength){
a = Arrays.copyOf(a, 2*currentLength);
}
a[size()] = o;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.