Question: For each question, write the method assuming that its part of the StringArrayList I started in lecture below : import java.util.ArrayList; public class StringArrayList implements
For each question, write the method assuming that its part of the StringArrayList I started in lecture below :
import java.util.ArrayList; public class StringArrayList implements StringListInterface {
String[] array; int size; public StringArrayList() {
size = 0;
array = new String[10];
}
@Override
public int size() {
return size;
}
@Override
public void add(String s) {
// make space if need
if(size == array.length) {
enlarge();
}
array[size] = s;
size++;
}
private void enlarge() {
// make a larger array
String[] larger = new String[array.length * 2];
// copy everything in
for(int i=0; i larger[i] = array[i]; } // set array to the larger array array = larger; } @Override public void add(int index, String s) throws IndexOutOfBoundsException { if(index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } // make space if need if(size == array.length) { enlarge(); } // move elements out of way for(int i = size; i>index; i--) { array[i] = array[i-1]; } // inser the elemt array[index] = s; } @Override public String get(int index) throws IndexOutOfBoundsException { if(index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return array[index]; } @Override public String remove(int index) throws IndexOutOfBoundsException { if(index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } // keep referce to removed thing String removed = array[index]; // shift everthing over for(int i=index; i array[i] = array[i+1]; } size -= 1; return removed; } } A. (2 points) Write a public void set(int i, String s) method that setsthe element of the list at index i to the value s. That is, it should overwrite the existing element at i. Be sure to handle exceptional conditions appropriately. B. (2 points) Write a public int indexOf(String s) method that searches the list for the first occurrence of a value equivalent to s (be careful with what kind of equality you use!), and returns its index. Return -1 if the value is not found. C. (1 point each) Suppose you instantiate a new StringArrayList. What are the size and the length of the backing array: 1) Right after instantiating the list. 2) After you add() 10 items to this list. 3)After you remove(0) five times from this list. Thank you!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
