Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For each question, write the method assuming that it’s part of the StringArrayLi

ID: 3889650 • Letter: F

Question

For each question, write the method assuming that it’s part of the StringArrayList we started in lecture.

A. (2 points) Write a public void set(int i, String s) method that sets the element of the list at index i to the value s. That is, it should overwritethe 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:

a) Right after instantiating the list.

b) After you add() 10 items to this list.

thank you!

c) After you remove(0) five times from this list.

Explanation / Answer

Java program:

import java.util.*;

public class StringArrayList

{

public static void main(String[]args)

{

ArrayList<String> list= new ArrayList<String>();

//Right after instantiating the list.

System.out.println("Size="+list.size());

//adding string elements to array list

list.add("First element");

list.add("Second element");

list.add("Third element");

//setting string at desired index- this is public void set(int i,String s) method

list.set(1, "Second-element replacement");

//public int indexOf(String s) method

int index=list.indexOf("Third element");

System.out.println("index="+index);

list.clear();//clearing operation in order to add ten elements to the list

//add() 10 items to the list

list.add("one");

list.add("two");

list.add("three");

list.add("four");

list.add("five");

list.add("six");

list.add("seven");

list.add("eight");

list.add("nine");

list.add("ten");

//Size after you add() 10 items to this list.

System.out.println("Size="+list.size());

//remove(0) five times from this list.

list.remove(0);

list.remove(0);

list.remove(0);

list.remove(0);

list.remove(0);

//Size after you remove(0) five times from this list.

System.out.println("Size="+list.size());

}

}

Output:

Size=0
index=2
Size=10
Size=5