₦airaland Forum

Welcome, Guest: Register • Login • With Google • Trending • Recent • New

Stats: 3,344,813 members, 8,513,816 topics. Date: Thursday, 05 November 2026 at 03:01 PM

Toggle theme

Karrigan's Posts

Nairaland Forum › Karrigan's Profile › Karrigan's Posts

1 (of 1 pages)

Programming › Help Req Wid Java Code. Doubt In ComparableTest Class. Qstn As Cmnt Below by karrigan(op): 10:16am On Jan 10, 2013
public class Student implements Comparable{
String firstName, lastName;
int studentID=0;
double GPA=0.0;
public Student(String firstName, String lastName, int studentID, double GPA){
if(firstName==null || lastName==null || studentID==0 || GPA ==0.0){
throw new IllegalArgumentException();
}
this.firstName=firstName;
this.lastName=lastName;
this.studentID=studentID;
this.GPA=GPA;
}
public String firstName(){
return firstName;
}
public String lastName(){
return lastName;
}
public int studentID(){
return studentID;
}
public double GPA(){
return GPA;
}
public int compareTo(Object o){
double f=GPA-((Student)o).GPA;
if(f==0){
return 0;
}
else if(f<0.0){
return -1;
}
else{
return 1;
}
}
}


import collections.Student;
import java.util.*;

public class ComparableTest {
public static void main(String ar[]){
TreeSet studentSet=new TreeSet();
studentSet.add(new Student("Mike", "Larry", 101, 4.0 ));
studentSet.add(new Student("William", "Costigan", 102, 2.8 ));
studentSet.add(new Student("Jamie", "Sullivan", 103, 3.6 ));
studentSet.add(new Student("Dan", "Costello", 104, 2.3 ));
Object[] studentArray=studentSet.toArray(); //why is object class used here and what does toArray() method do?
Student s;
for(Object obj: studentArray){
s=(Student)obj;
System.out.printf("Name = %s %s ID = %d GPA = %.1f\n", s.firstName(), s.lastName(), s.studentID(), s.GPA());
}
}
}



/*Output
Name = Dan Costello ID = 104 GPA = 2.3
Name = William Costigan ID = 102 GPA = 2.8
Name = Jamie Sullivan ID = 103 GPA = 3.6
Name = Mike Larry ID = 101 GPA = 4.0
BUILD SUCCESSFUL (total time: 0 seconds)
*/

1 (of 1 pages)