public class Person implements Comparable<Person> { // the age of the person private int age; //the name of the person private String name; //the Integer object to wrap the age value; private Integer ageWrap; //Constructor and accessors methods omitted. . . . /** * Compare the ages of the persons */ public int compareTo(Person person) { return getAgeWrap().compareTo(person.getAgeWrap()); } } import java.util.*; public class PersonTreeSet { // instance variables private TreeSet<Person> setOfPersons; private String[] persons = {"Vasilis", "Jenny", "Varvara", "Thanasis", "Dimitris", "Dionisia", "Kostas", "Eugenia", "Hara", "Antonia"}; private int maxAge; //Constructor and main method omitted. . . . /** * Create people and add them in the TreeSet */ public void createPersons() { Random rand = new Random(); for(int index = 0; index < persons.length; index++) { Person person = new Person(rand.nextInt(maxAge), persons[index]); setOfPersons.add(person); } System.out.println(setOfPersons.size()); } /** * Print all the elements of the treeSet */ public void printPersons() { for(Person person : setOfPersons) { System.out.println(person.getName() + " is " + person.getAge() + " years old"); } } /** * sort persons by age. */ public void sortByAge() { ArrayList<Person> sortPersons = new ArrayList<Person>(); sortPersons.addAll(setOfPersons); Collections.sort(sortPersons); for(Person person : sortPersons) { System.out.println(person.getName() + " is " + person.getAge() + " years old"); } } }
This is the exercise I am trying to solve. And this is as far as I have gotten to.The collection library has a class named TreeSet, which is an example of
a sorted set. Elements in this set are kept in order. Carefully read the description of this class,
and then write a class Person that can be inserted into a TreeSet, which will then sort the
Person objects by age.
Is it possible to sort my setOfPersons TreeSet directly? I tried to usemethod but it wont compile, and I realized that it is not applicable to TreeSet. So I made theCollections.sort(setOfPersons)method to do it indirectly...sortByAge()
I am puzzled though because in the exercise it statesmeaning that the TreeSet will sort the Person Objects and not my class..write a class Person that can be inserted into a TreeSet, which will then sort the Person objects by age.
Any suggestions?