KaiquanMah's picture
class MinMax<T extends Comparable<T>>
a679cd0 verified
Write a generic class
class MinMax<T extends Comparable<T>>
...where the implementing type must implement the Comparable interface.
The class has the following properties:
1
A constructor that takes a list as a parameter. The list contains elements of type T.
2
A method public T smallest(), which returns the smallest element in the list.
3
A method public T largest(), which returns the largest element in the list.
4
The comparison of list elements uses the services provided by the Comparable interface.
Tip: Check out the Collections class API description - there are a couple of useful operations for finding the smallest or largest element...
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
System.out.println("Testing the MinMax class...");
System.out.println("Testing with integers");
int n = -r.nextInt(200);
ArrayList<Integer> numbers = new ArrayList<>();
int count = r.nextInt(10) + 10;
for (int i = 0; i < count; i++) {
numbers.add(n);
n += r.nextInt(40);
}
Collections.shuffle(numbers, r);
System.out.println("List:" + numbers);
System.out.println("Creating object...");
MinMax<Integer> mm = new MinMax<>(numbers);
System.out.println("Object created!");
System.out.println("Smallest: " + mm.smallest());
System.out.println("Largest: " + mm.largest());
System.out.println("");
System.out.println("Testing with floating-point numbers");
double n2 = -r.nextInt(240);
ArrayList<Double> numbers2 = new ArrayList<>();
Double[] d = {0.0, 0.25, 0.5, 0.75};
count = r.nextInt(10) + 10;
for (int i = 0; i < count; i++) {
n2 += r.nextInt(40) + d[r.nextInt(d.length)];
numbers2.add(n2);
}
Collections.shuffle(numbers2, r);
System.out.println("List:" + numbers2);
System.out.println("Creating object...");
MinMax<Double> mm2 = new MinMax<>(numbers2);
System.out.println("Object created!");
System.out.println("Smallest: " + mm2.smallest());
System.out.println("Largest:" + mm2.largest());
}
}
//ADD
class MinMax<T extends Comparable<T>> {
private ArrayList<T> list;
public MinMax(ArrayList<T> list) {
this.list = list;
}
public T smallest() {
return Collections.min(list);
}
public T largest() {
return Collections.max(list);
}
}
Testing the MinMax class...
Testing with integers
List:[104, 197, 159, 178, 106, 164, 33, -20, 11, 47, 130, 209, 84, 107, 198, -51]
Creating object...
Object created!
Smallest: -51
Largest: 209
Testing with floating-point numbers
List:[207.5, 6.0, 151.0, 256.75, 115.5, 205.0, 292.75, 24.25, 180.25, 83.0, 74.0, 6.0, 41.0, 33.75, 231.0]
Creating object...
Object created!
Smallest: 6.0
Largest:292.75