import java.util.*;
public class Employee
{
private int empId;
private String name;
private int age;
public Employee(String name, int id, int age )
{
this.name = name;
this.empId = id;
this.age = age;
}
public int getId()
{
return empId;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
}
class SortById extends Employee implements Comparable<SortById>
{
public SortById(String name, int id, int age)
{
super(name, id, age);
}
public int compareTo(SortById other)
{
if (this.getId() > other.getId()) return 1;
if (this.getId() < other.getId()) return -1;
return 0;
}
}
class SortByName extends Employee implements Comparable<SortByName>
{
public SortByName(String name, int id, int age)
{
super(name, id, age);
}
public int compareTo(SortByName other)
{
if (this.getName().compareTo(other.getName()) > 0) return 1;
if (this.getName().compareTo(other.getName()) < 0) return -1;
return 0;
}
}
class Test
{
public static void main(String args[])
{
Employee[] array = new SortById[3];
array[0] = new SortById("Gautam", 1222, 20);
array[1] = new SortById("Shivam", 1221, 20);
array[2] = new SortById("Ankit", 1223, 21);
System.out.println(array[0] instanceof SortByName);
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
System.out.println("ID: " + array[i].getId() + " Name: " + array[i].getName() + " Age: " + array[i].getAge());
Employee[] array2 = new SortByName[3];
array2[0] = new SortByName("Gautam", 1222, 20);
array2[1] = new SortByName("Shivam", 1221, 20);
array2[2] = new SortByName("Ankit", 1223, 21);
Arrays.sort(array2);
for (int i = 0; i < array2.length; i++)
System.out.println("ID: " + array2[i].getId() + " Name: " + array2[i].getName() + " Age: " + array2[i].getAge());
}
}
This program runs fine, I just wanted to ask since I’m using the parameterized version of Comparable, should the reference I pass into the compareTo be of SortById type or SortByName type?
The code runs fine even if the reference is of type Employee, although pointing to its subclass (SortByName or SortById).
How is an implicit cast happening? I have read is not possible i.e., it’s not possible to cast a superclass type to subclass implicitly.
You never call
compareTowhich explains why you don’t need the cast. The actual call is withinArrays.sortwhich takes care of it (by actually using the rawComparable)Also, in such a case the compiler will generate 2
compareTomethods: the one you explicitly define with theSortByXXparameter, and another one with anObjectparameter which delegates to the first one.As @martijno says it, you will run into problems if you add a simple
Employeein your array, which will lead toClassCastException(fromEmployeeto eitherComparableorSortByXX). Same will occur if you mixSortByNameandSortById.