Question: Please add the following three methods to our ArrayList class (i.e. StringArrayList.java): 1.void clear(): This method is used to remove all the elements from any
Please add the following three methods to our ArrayList class (i.e. StringArrayList.java):
1.void clear(): This method is used to remove all the elements from any list.
2.int indexOf(String str): The method returns the first occurrence of a given element, or returns -1 in case the element is not on the list.
3.int lastIndexOf(String str): The method returns the last occurrence of a given element, or returns -1 in case the element is not on the list.
import java.util.Arrays;
public class StringArrayList implements myList{
private String[] theData;
private int size = 0;
//the number of elements in the current list
//the next position to add data
private int capacity = 0;
private static final int INITIAL_CAPACITY = 5;
public StringArrayList(){
theData = new String[INITIAL_CAPACITY];
capacity = INITIAL_CAPACITY;
}
@Override
public void add(String value) {
if(size>=capacity){
//full; create a new one
reallocate();
theData[size]=value;
size++;
}else{
theData[size]=value;
size++;
}
}
private void reallocate(){
capacity = capacity * 2;
theData = Arrays.copyOf(theData, capacity);
}
@Override
public void add(int index, String value) {
if(index < 0 || index > size){
throw new
ArrayIndexOutOfBoundsException(index);
}
if(size>=capacity){
reallocate();
}
for(int i = size - 1; i >= index; i--){
theData[i+1] =theData[i];
}
theData[index] = value;
size++;
}
public interface myList { public void add(String value); public void add(int index, String value); public String remove(int index); public String get(int index); public String set(int index, String value); } public class Test {
public static void main(String[] args) {
StringArrayList testList = new StringArrayList();
testList.add("Alice");
testList.add("Cher");
testList.add("David");
testList.add("Ellen");
testList.add(1,"Bob");
testList.add("Frank");
testList.remove(1);
testList.set(1, "Joseph");
testList.traverse();
System.out.println("The value at index 2 is " +
testList.get(2));
//testList.set(10, "Hugh");
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
