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

1) Using wildcards, write a generic method that counts the number of even number

ID: 3710786 • Letter: 1

Question

1) Using wildcards, write a generic method that counts the number of even numbers in a List. This method should accept Lists with elements that inherit from Integer.

2) Write the skeleton of a generic class called MyList. MyList represents a list that can be created to hold elements of type String (or subclasses of String). MyList should have the following methods: add (takes an element as input, returns nothing), remove (takes an element as input, returns nothing), indexOf (takes an element as input, returns an integer index), get (takes an integer index as input, returns an element). The skeleton of the class should contain the class definition (ex: class Test {}) and the method definitions (ex: void testMethod(int testInput)). Writing the implementation for the methods is unnecessary.

Explanation / Answer

Question 1: Generic method to count no. of even numbers

public <T extends Integer> int countEven(List<T> numbers)
{
int count = 0;
for(int i = 0; i < numbers.size(); i++)
{
if(numbers.get(i) % 2 == 0)
count++;
}
return count;
}
===========================


Question 2: The class skeleton is given below. The implementation is not provided since the questions says no implementation is needed.

public class MyList1<T extends String> {

void add(T element)
{

}

void remove(T element)
{

}

int indexOf(T element)
{

}

T get(int index)
{

}
}