Java public interface Comparable{ //T is an arbitrary type //returns -1,0,1 as t
ID: 3873361 • Letter: J
Question
Java
public interface Comparable{ //T is an arbitrary type
//returns -1,0,1 as this T is < ,==, > when compared to other
public int compareTo(T other);
}
The above code is basically the entire code for java.util.Comparable.
1) Write a method minInArray(that would appear in some arbitrary class) that is passed an array of Comparables and returns a reference to the smallest one.
2) Make the following class Employee Comparable. If passed to minInArray, it should return the Employee with the shortest name
public class Employee{
private String name, boss;
private int rating;
public String getName(){
return name;
} //other stuff ............
Explanation / Answer
Employee.java
public class Employee implements Comparable
{
private String name,boss;
private int rating;
public Employee(String name, String boss, int rating)
{
this.name = name;
this.boss = boss;
this.rating = rating;
}
public String getName()
{
return this.name;
}
@Override
public int compareTo(Object o)
{
Employee e = (Employee) o;
if(this.name.length()<e.name.length())
return -1;
else if(this.name.length()==e.name.length())
return 0;
else
return 1;
}
public static Employee minInArray(Employee[] employees)
{
Employee minE = employees[0];
for(int i=1;i<employees.length;i++)
{
if(employees[i].compareTo(minE)==-1)
minE = employees[i];
}
return minE;
}
}
Driver.java
import java.util.*;
public class Driver {
public static void main(String[] args)
{
Employee e1 = new Employee("A","BE",5);
Employee e2 = new Employee("BE","CEE",4);
Employee e3 = new Employee("CEE","D",5);
Employee[] arr = {e1,e2,e3};
Employee small = Employee.minInArray(arr);
System.out.println(small.getName());
}
}
Explanation
since we have declared that the Employee class implements comparable interface, we will have to override the compareTo method which has been declared in that interface.
In the compare to method we decide the smaller among two parameters(implicit and explicit ) by the length of their name instance variables, returning -1,0,1 as necessary.
to test this function we define another function minInArray to find out the employee having name of shortest length.
We call this method by supplying it an array of Employee objects and then printing the name instance variable of the Employee object with the shortest length of the name instance field.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.