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 Person
and 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".
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.