Write a generic class named MyList, with a type parameter T. The type parameter
ID: 3633168 • Letter: W
Question
Write a generic class named MyList, with a type parameter T. The type parameter T should be constrained to an upper bound: the Number class. The class should have as a field an ArrayList of T. Write a public method named add, which accepts a parameter of type T. When an argument is passed to the method, it is added to the ArrayList. Write two other methods, largest and smallest, which return the largest and smallest values in the ArrayList.Explanation / Answer
Here is the program. /* * Simple program for generic types in java. * Methods to implement largest and smallest values in list. */ import java.util.ArrayList; import java.util.Iterator; class NoElementException extends Exception{ private static final long serialVersionUID = 1L; public String getMessage(){ String error = "No elements in MyList"; return error; } public String toString(){ return getMessage(); } } /** * The Class MyList. * * @param the generic type bounded to number */ public class MyList { /** The list to hold elements. */ ArrayList list = new ArrayList(); /** * Adds the element to list. * * @param t the t */ public void add(T t){ list.add(t); } /** * Finds Largest element in list. * * @return the t * @throws NoElementException if no elements are in list */ public T largest() throws NoElementException{ if(list.isEmpty()){ NoElementException e = new NoElementException(); throw e; } Iterator i = list.iterator(); T largest = i.next(); while(i.hasNext()){ T temp = i.next(); if(temp.doubleValue() > largest.doubleValue()){ largest = temp; } } return largest; } /** * Smallest. * * @return the t * @throws NoElementException the no element exception */ public T smallest() throws NoElementException{ if(list.isEmpty()){ NoElementException e = new NoElementException(); throw e; } T smallest = list.get(0); for (T temp : list){ if(temp.doubleValue()Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.