In: Computer Science
The collections library has a class TreeSet (java.util.TreeSet). It is another parameterised class which is an example of a sorted set. That is, elements in this set are kept in order. Construct classes Person and PersonCompator to make the following code successfully compile and run. This method checks if Person objects are correctly ordered by their ages (age is the only attribute of Person). PersonComparator is required to implement interface Comparator (java.util.Comparator). Comparator is another parameterised interface -- parameterization is common in Java.
Set<Person> persons = new TreeSet<Person>(new PersonComparator());
persons.add(new Person(32));
persons.add(new Person(17));
persons.add(new Person(13));
persons.add(new Person(35));
Iterator<Person> iter = persons.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
Person.java
class Person {
// private variable age
private int age;
// parameterized constructor
public Person(int age) {
this.age = age;
}
// getter
public int getAge() {
return age;
}
// to String returns the information about person
@Override
public String toString() {
return "Person [age=" + age + "]";
}
}
PersonComparator.java
public class PersonComparator implements Comparator<Person> {
// comparing two persons based on age
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
Main.java
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
// creating persons set
Set<Person> persons = new TreeSet<Person>(new PersonComparator());
// adding persons objects
persons.add(new Person(32));
persons.add(new Person(17));
persons.add(new Person(13));
persons.add(new Person(35));
// initializing persons to iterator
Iterator<Person> iter = persons.iterator();
// printing all persons details
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
Code
Person.java
PersonComparator.java
Main.java
Output