Math 140 Programming Assignment2 5. String getint index)-If index = size then th
ID: 3749876 • Letter: M
Question
Math 140 Programming Assignment2 5. String getint index)-If index = size then throw an IndexOutOfBoundsException. Otherwise, return the String object stored at position index. 6. int size() - return the value of size 7. String toString() - returns a String representation of the list. Example: suppose the array contains the values "xyz", "cat", and "ABC". The toString method returns the String f"xyz", "cat"', "ABC"). If the list is empty return the String 0. "ABC"). If the list is empty return the String 8. StringArrayList containsPrefix(String pre) - returns a StringArrayList object that starts with the String stored in pre.Explanation / Answer
import java.util.*;
public class Demo{
public static void main (String[] args) {
ArrayList<String> arr=new ArrayList<String>();
arr.add("Hello");
arr.add("Hell");
System.out.println(arr); // ArrayList itself Overrides the toString method
System.out.println(arr.get(1)); // Available in ArrayList, will return the String at index 1
System.out.println(arr.size()); // Available in ArrayList, will return size of ArrayList
System.out.println(containsPrefix("Hello",arr)); // created below
}
public static ArrayList containsPrefix(String pre,ArrayList <String> arr){
ArrayList b=new ArrayList();
for(String a:arr){
if(a.length()>=pre.length())
if(pre.equals(a.substring(0,pre.length())))
b.add(a);
}
return b;
}
}