how to sort a Vector that stores a particular object type, by an attribute?
Hi guys,
i need help on this problem that i'm having. i have a vector that stores a particular object type, and i would like to sort the elements in that vector alphabetically, by comparing the attribute contained in that element. here's the code:
Class that creates the object
public class Patient {
private String patientName, nameOfParent, phoneNumber;
private GregorianCalendar dateOfBirth;
private char sex;
private MedicalHistory medHistory;
public Patient (String patientName, String nameOfParent, String phoneNumber, GregorianCalendar dateOfBirth, char sex) {
this.patientName = patientName;
this.nameOfParent = nameOfParent;
this.phoneNumber = phoneNumber;
this.dateOfBirth = dateOfBirth;
this.sex = sex;
this.medHistory = new MedicalHistory();
}
}
Class that creates the Vector.
public class PatientDatabase {
private Vector <Patient> patientDB = new Vector <Patient> ();
private DateFunction date = new DateFunction();
public PatientDatabase () throws IOException{
String textLine;
BufferedReader console = new BufferedReader(new FileReader("patient.txt"));
while ((textLine = console.readLine()) != null) {
StringTokenizer inReader = new StringTokenizer(textLine,"\t");
if(inReader.countTokens() != 7)
throw new IOException("Invalid Input Format");
else {
String patientName = inReader.nextToken();
String nameOfParent = inReader.nextToken();
String phoneNum = inReader.nextToken();
int birthYear = Integer.parseInt(inReader.nextToken());
int birthMonth = Integer.parseInt(inReader.nextToken());
int birthDay = Integer.parseInt(inReader.nextToken());
char sex = inReader.nextToken().charAt(0);
GregorianCalendar dateOfBirth = new GregorianCalendar(birthYear, birthMonth, birthDay);
Patient newPatient = new Patient(patientName, nameOfParent, phoneNum, dateOfBirth, sex);
patientDB.addElement(newPatient);
}
}
console.close();
}
}
*note that the constructor actually reads a file and tokenizes each element to an attribute, and each attribute is passed through the constructor of the Patient class to instantiate the object. it then stores the object into the vector as an element.
based on this, i would like to sort the vector according to the object's patientName attribute, alphabetically. can anyone out there help me on this?
i have read most of the threads posted on this forum regarding similar issues, but i don't really understand on how the concept works and how would the Comparable be used to compare the patientName attributes.
Thanks for your help, guys!

