Highest and Lowest Elements: Write a generic class with a type parameter constra
ID: 3759020 • Letter: H
Question
Highest and Lowest Elements: Write a generic class with a type parameter constrained to any type that implements Comparable. The constructor should accept an array of such objects. The class should have methods that return the highest and lowest values in the array. Demonstrate the class in an application.
// TODO this type parameter must be constrained
public class HighLow<T> {
// TODO declare field(s)
public HighLow(T[] values) {
// TODO implement
}
public T getHighest() {
// TODO implement
return null;
}
public T getLowest() {
// TODO implement
return null;
}
public static void main(String[] args) {
Integer[] numbers = {44, 77, 11, 99, 55, 22};
// Create a HighLow object.
HighLow<Integer> highLow = new HighLow<>(numbers);
// Display the highest value in the array.
System.out.println("The highest value is " +
highLow.getHighest());
// Display the lowest value in the array.
System.out.println("The lowest value is " +
highLow.getLowest());
}
}
Explanation / Answer
// TODO this type parameter must be constrained
public class HighLow<T extends Comparable<T>> {
// TODO declare field(s)
private T[] data;
public HighLow(T[] values) {
// TODO implement
data = values;
}
public T getHighest() {
// TODO implement
T highest = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i].compareTo(highest) > 0) {
highest = data[i];
}
}
return highest;
}
public T getLowest() {
// TODO implement
T lowest = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i].compareTo(lowest) < 0) {
lowest = data[i];
}
}
return lowest;
}
public static void main(String[] args) {
Integer[] numbers = {44, 77, 11, 99, 55, 22};
// Create a HighLow object.
HighLow<Integer> highLow = new HighLow<>(numbers);
// Display the highest value in the array.
System.out.println("The highest value is " +
highLow.getHighest());
// Display the lowest value in the array.
System.out.println("The lowest value is " +
highLow.getLowest());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.