searching objects in a vector according to an object data member

Hello,

I must admit that i am a rookie java programmer desperate for your help.

I have made a class that describes a college student.This is the part that matters for my problem

import java.util.*;

public class student

{

Integer idnumber;

Date dateofrecording;

String surname;

String name;

String fathersname;

String mothersname;

String placeofbirth;

Date dateofbirth;

Vector grades;

}

In an other class which is the office of the college, there is a "vector" called students in which the objects "student" will be kept.

I sort the students in this vector according to their idnumber using the Collections.sort(students, student.mitr) method where the comparator student.mitr is the following:

static public final Comparator mitr = new Comparator()

{

public int compare(Object o1, Object o2)

{

if(o1==o2) return 0;

student s1 = (student)o1;

student s2 = (student)o2;

return s1.idnumber.compareTo(s2.idnumber);

}

public boolean equals(Object obj)

{

return super.equals(obj);

}

};

I am using the : int index = Collections.binarySearch(students , idnum , student.mitr); (idnum is an Integer) to search for a student according to it's idnumber but it doesn't work.

I would be gratefull for your help.

[1432 byte] By [dimopule] at [2007-9-26 2:37:31]
# 1

For the binary search to work, the collection must be sorted, for a start. Which means you need to run Collections.sort() first.

To do that, you need to have students implement the Comparable interface or implement a Comparator. Those are very similiar, and it's really up to you what to use. I would think you would just implement Comparator.

public int compareTo( Object o ) {

return ( o instanceof Student ) ?

idnumber.compareTo( ((Student)o).idnumber ) :

-1;

}

You will also need want to implement equals(). That would be pretty simple.

public boolean equals( Object o ) {

return compareTo( o ) == 0;

}

Now sort and binary search should work.

ShagVT at 2007-6-29 10:06:58 > top of Java-index,Archived Forums,Java Programming...
# 2

Try taking the equals() method out of the comparator. If that doesn't work, add the following to your Student class and try it...

class Student {

...

public boolean equals(Object obj) {

if(this==obj) return true;

if( (obj==null) || (this.getClass() != obj.getClass()) )

return false;

Student s = (Student)obj;

return this.idnum.equals(s.idnum);

}

...

}

CWalker807 at 2007-6-29 10:06:58 > top of Java-index,Archived Forums,Java Programming...