Math 140 Programming Assignment2 Public Methods 1. void add(String value) If siz
ID: 3749874 • Letter: M
Question
Math 140 Programming Assignment2 Public Methods 1. void add(String value) If size 2 list.length then call the ensureCapacity method to double the size of the list array. After guaranteeing the list array has sufficient capacity, insert value at position size in the list array and then increase size by 1. Example: Suppose list - ("xyz", "cat", "123", nul) and size 3. After calling add("'ABC"), list - ["'xyz", "cat", "123", "ABC") and size 4. 2. void add(int index, String value) If index size then throw an IndexOutOfBoundsException. If size 2 list.length then call the ensureCapacity method to double the size of the list array. After guaranteeing the list array has sufficient capacity, insert value at position index in the list array and then increase size by 1. Example of throwing the exception: if (index size) throw new IndexOutOfBoundsException); Example: Suppose list = {"xyz", "cat", "123"). After calling add(2, "ABC"), list ("xyz", "cat", "ABC", "123") 3. String remove(int index) If index - size then throw an utofBoundsException. Otherwise, remove the value stored at index by hifting the values stored in list to the left, decrease size by 1, and return the String removed by the method. Example: Suppose list f"xyz", "cat"', "ABC", "123") and size 4 After calling remove(2), list - ("xyz", "cat", "123"), size 3, return "ABC" 4. boolean remove(String s) If s is in the list then remove the first occurrence of s decrease size by 1, and return true. Otherwise, return false. Example: Suppose list - ("xyz", "cat", "ABC" "123"), size 4 After calling remove("ABC"), list ("xyz", "cat", "123"), size 3, return trueExplanation / Answer
#...written in python...
def add( value ):
if( size>= list.length ):
list.ensureCapacity()
list.insert( size, value )
size++
def add( index, value ):
if( index<0 or index>size ):
throw new IndexOutOfBoundException()
if( size>= list.length ):
list.ensureCapacity()
list.insert( index, value ) #this function inserts elements at index position
size++
def remove( index ):
if( index<0 or index>size ):
throw new IndexOutOfBoundException()
var item = list[index] #store the item in local var before deleting
list.pop(index)
#list are automatically shifted to left in python
size--
return item #return the stored variable
def remove(s):
if s in list:
list.pop(s)
#pop funtion automatically removes the first occurance of the element in list
size--
return true
else:
return false