I have a student object which implements Comparable interface.
class Student implements Comparable<Student>{
String rollNo;
double internal;
double external;
Student(String rollNo, double internal, double external){
this.rollNo = rollNo;
this.internal = internal;
this.external = external;
}
public int compareTo(Student otherStudent){
return (this.external < otherStudent.external) ? -1 :
(this.external > otherStudent.external) ? 0 : 1;
}
}
I am trying to add a set of objects from a list of students. The snippet of the input list is as follows:
U4CSE11150,25,24.5
U4CSE11167,4,13
U4CSE12502,23,34.5
U4CSE13001,27,44.5
U4CSE13002,26,30
U4CSE13003,44,62.5
U4CSE13005,32,30.5
U4CSE13006,24,31
U4CSE13007,27,41
U4CSE13008,34,47
...
I am creating Student object within a while loop, adding it to the TreeSet studentsand printing the size of Treesetalong with the 3rd value of the object (that is external mark). The following is the code.
while((line = br.readLine()) != null){
String[] elements = line.split(",");
rollNo = elements[0];
internal = Double.parseDouble(elements[1]);
external = Double.parseDouble(elements[2]);
Student s = new Student(rollNo, internal, external);
students.add(s);
System.out.println("Size: " + students.size() + " Mark: "
+ s.external);
}
But, when running the program, I am getting the output like follows. It is adding only first two objects.
Size: 1 Mark: 24.5
Size: 2 Mark: 13.0
Size: 2 Mark: 34.5
Size: 2 Mark: 44.5
Size: 2 Mark: 30.0
Size: 2 Mark: 62.5
Size: 2 Mark: 30.5
Size: 2 Mark: 31.0
Size: 2 Mark: 41.0
Can anybody help me out? Thanks in advance.
Your compareTo method is invalid - you return 0 when the compared values are not equal. It should be :
public int compareTo(Student otherStudent){
return (this.external < otherStudent.external) ? -1 :
(this.external > otherStudent.external) ? 1 : 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With