In: Computer Science
Behold, the power of interfaces! On this homework problem you'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface.
Create a public class named Max with a single class method named max. max should accept an array of Objects that implement Comparable and return the maximum. If the array is null or empty, you should return null.
You will probably need to review the documentation for Comparable.
Explanation:I have implemented the Max class with the max method,Customer class and Demo class,I have found the customer with the maximum id using the generic max() method that accepts a generic array that implements the Comparable object and it can return the maximum element of all the objects that are comparable.I have shown the output of the program, please find the images attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//Max class
public class Max {
public <E extends Comparable<E>> E max(E[] arrayOfObjects) {
if (arrayOfObjects == null ||
arrayOfObjects.length == 0)
return
null;
E maxElement =
arrayOfObjects[0];
for (E arrayElement :
arrayOfObjects) {
if
(arrayElement.compareTo(maxElement) > 0) {
maxElement = arrayElement;
}
}
return maxElement;
}
}
//Customer class
public class Customer implements Comparable<Customer> {
Integer idCustomer;
String name;
String gender;
String email;
public Customer() {
}
public Customer(Integer idCustomer, String name,
String gender,
String email)
{
this.idCustomer = idCustomer;
this.name = name;
this.gender = gender;
this.email = email;
}
@Override
public String toString() {
return "Customer [idCustomer=" +
idCustomer + ", name=" + name
+ ", gender=" + gender + ", email=" + email +
"]";
}
@Override
public int compareTo(Customer o) {
return
idCustomer.compareTo(o.idCustomer);
}
}
//Demo class
public class Demo {
public static void main(String[] args) {
Max maxObj = new Max();
Customer customer1 = new
Customer(1111, "Mr.Roy", "male", "abdc.com");
Customer customer2 = new
Customer(121, "Mr.Root", "male", "adfbc.com");
Customer customer3 = new
Customer(1451, "Mrs.Lily", "female",
"sgh.com");
Customer customer4 = new
Customer(12511, "Mr.Henry", "male", "gdd.com");
Customer customers[] = {customer1,
customer2, customer3, customer4};
Customer maxIdCustomer =
maxObj.max(customers);
System.out
.println("The details of the customer having
maximimum id is:");
System.out.println(maxIdCustomer.toString());
}
}
Output: