-1

This is a question which needs to be answered using the methods shown here and no other way (its a exam question).

I have a Personand Friends(TreeSet to hold Person) class

The Person class just creates a instance of person with a sName and fName.

In friends I have a method getSurname() which finds the surname of the object Person and adds it to a new set with all matching surnames:

//Gets the surname of the object and create a new set
public TreeSet<Person> getSurname(String s){
    TreeSet<Person> surname = new TreeSet<Person>();

    for(Person currentPerson : friendsSet) { 
        if(currentPerson.getsName().equals(s)) {
            surname.add(currentPerson);
        }
    }

    return surname;

}

public String toString() {
    return "Friends [friendsSet=" + friendsSet + "]";
}

The problem occurs when in main I call the toString() method

public static void main(String[] args) {
        Friends f = new Friends();  

        f.add(new Person("Rosella", "Murphy"));
        f.add(new Person("Mary", "O Keefe"));


        f.add(new Person("Rosella", "O Keefe"));
        //toString here
        System.out.printf("There should be 2 people with the surname 'O Keefe: %s",f.getSurname("O Keefe").toString());
}

It only prints out "Mary", "O Keefe" it should also print out "Rosella", "O Keefe".

enter image description here

I am returning a new TreeSet(getSurname()) with the surnames that match the parameter used in the method.

Then calling the method and then calling toString() method to print all the names in the new list.

Sean
  • 43
  • 4

1 Answers1

0

Without seeing the implementation of the Person class, I can't debug your exact issue, but likely your problem lies in your implementation of the compareTo(Person p) method from the Comparable interface.

If you have something like this in your compareTo function:

@Override
public int compareTo(Person p) {
    return sName.compareTo(p.sName);
}

Then the TreeSet will see both Person("Mary", "O Keefe") and Person("Rosella", "O Keefe") Person objects as the same object.

The reason for this is because a Set only contains unique elements. It uses the compareTo function to determine whether an element already exists in the set.

To fix this issue, you will need to compare with both the first name and surname like so:

@Override
public int compareTo(Person p) {
    return fName.compareTo(p.fName) + sName.compareTo(p.sName);
}
leah
  • 16
  • 4