/* WHEN IS COMPARETO METHOD CALLED, WHY DO WE NEED TO PUT ELEMENTS OF TREESET IN TO AN OBJECT ARRAY AND THEN TYPE CAST IT.
*/
import java.util.*;
class Comparable1
{
public static void main(
String[] args)
{
TreeSet ts1=new TreeSet();
ts1.add(new Student("Saurabh","Thard",100,0.1));
ts1.add(new Student("Sachin","Tendulkar",200,0.01));
ts1.add(new Student("Prannoy","Roy",300,03.03));
ts1.add(new Student("Barkha","Dutt",400,04.4));
ts1.add(new Student("Vikram","Chandra",500,5.05));
Object [] studArray=ts1.toArray();
Student s;
for(Object obj:studArray)
{
s=(Student) obj;
System.out.printf("NAME = %s %s STUDENT ID =%d GPA=%.1f \n",s.fname(),s.lname(),
s.StudentID(),s.gpa());
}
}
}
class Student implements Comparable
{
String fname;
String lname;
int studentID;
double gpa;
public Student(String fname,String lname,int studentID,double gpa)
{
if(fname==null || lname==null || studentID==0 || gpa==0.0)
{
throw new IllegalArgumentException();
}
this.fname=fname;
this.lname=lname;
this.studentID=studentID;
this.gpa=gpa;
}
public String fname()
{
return fname;
}
public String lname()
{
return lname;
}
public int StudentID()
{
return studentID;
}
public double gpa()
{
return gpa;
}
public int compareTo(Object o) //OVER-RIDING COMPARETO SINCE IT IMPLEMENTS COMPARABLE.
{
double f= gpa- ((Student)o).gpa;
if(f==0.0)
return 0;
else if(f<0.0)
return -1;
else
return 1;
}
}