1
public int compareTo(Object o) {
    Doctor d = (Doctor)o;
    return (doctor_name.compareTo(d.doctor_name));
}

This is my comparable in Doctor class

jTextArea.setText("");
int doctor_id = Integer.parseInt(jTextField2.getText());
String doctor_name = jTextField3.getText();
String hospitalName = jTextField4.getText();

Doctor d = new Doctor(doctor_id,doctor_name,hospitalName);
hmDoctor.put(doctor_id, d);

This is my hashmap

and this is my tree map

TreeMap<Integer,Doctor> tmDoctor = new TreMap<Integer,Doctor>(hmDoctor);
jTextArea.setText("");
Set keys = tmDoctor.keySet();
Iterator<Integer> ite = keys.iterator();

while(ite.hasNext())
{
    int doctorID = ite.next();
    Doctor d = tmDoctor.get(doctorID);
    tmDoctor.put(doctorID, d);
    jTextArea1.append(d.toString());
}

It doesn't sort doctor names. Why?

1 Answer 1

10

The TreeMap sorts elements according to their keys, not values. As an alternative, you could use a TreeMap<String, Doctor> indexed by the doctor's name. Or, depending on what you need to do, you can just keep the doctors in a TreeSet.

4
  • 1
    i can do that with tree set by doctorName isnt it ? Nov 20, 2011 at 21:18
  • If you were to go with a set, it would be a sorted collection of doctors (you'd probably have to override equals() as well), which would allow tests such as yourSet.contains(d). If you go with the map by name, you could do yourMap.get("Gregory House") to get the Doctor object.
    – Vlad
    Nov 20, 2011 at 21:21
  • private TreeMap<String, Doctor> tmDoctor = new TreeMap<String,Doctor>(); if i do that and it works now but whats the meaning of Comparable in Doctor class ? Nov 20, 2011 at 21:30
  • The fact that Doctor implements Comparable would allow it to to appear in a TreeSet<Doctor> or a TreeMap<Doctor,...> i.e. serve as a key for the tree rather than a value. It would also mean that you could use Arrays.sort() on a Doctor[].
    – Vlad
    Nov 20, 2011 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.