Question

In: Computer Science

The collections library has a class TreeSet (java.util.TreeSet). It is another parameterised class which is an...

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());
}

Solutions

Expert Solution

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


Related Solutions

JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of       ...
JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of        * the comparator is to compare the alphabetic order of integers. With Q3,        * the order of Integer elements will be sort according to the order of        * digit Unicode.        * For example, the value of {11,3,31,2} will return {11,2,3,31}        * NOTE: You don't need to compare each digit one by one. Just compare them System.out.println("Q3...
using java Define a class Library based on the following specifications: a. A library can have...
using java Define a class Library based on the following specifications: a. A library can have multiple books. Decide on the best possible data structure to store books. b. A library has a name. c. A library has an address. Define a 2-argument constructor for the Library class. Decide on the arguments needed for this constructor. e. Define a method that can add new books to the library. f. Define a method that allows a book to be borrowed (checked...
C++: Write a student class for the library, which have the following: Username, password, Maximum number...
C++: Write a student class for the library, which have the following: Username, password, Maximum number of copies that a student is allowed to keep(less than 5), maximum borrow periods(less than 30 days per book), list of copy(array) cpp and h
java programming Concepts ArrayList - Collections Sorting Enhanced For Loop Collections Class Auto-boxing Programming Assignment 1....
java programming Concepts ArrayList - Collections Sorting Enhanced For Loop Collections Class Auto-boxing Programming Assignment 1. Describe auto-boxing, including why it is useful. (Google for this one) Write a few lines of code that auto-box an int into an Integer, and un-box an Integer to an int. 2. Declare an ArrayList of Strings. Add 5 names to the collection. "Bob" "Susan" ... Output the Strings onto the console using the enhanced for loop. 3. Sort the list using the method...
In this homework you will implement a Library class that uses your Book and Person class...
In this homework you will implement a Library class that uses your Book and Person class from homework 2, with slight modifications. The Library class will keep track of people with membership and the books that they have checked out. Book.java You will need to modify your Book.java from homework 2 in the following ways: field: dueDate (private)             A String containing the date book is due.  Dates are given in the format "DD MM YYYY", such as "01 02 2017"...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside...
JAVA program Create a class called Array Outside of the class, import the Scanner library Outside of main declare two static final variables and integer for number of days in the week and a double for the revenue per pizza (which is $8.50). Create a method called main Inside main: Declare an integer array that can hold the number of pizzas purchased each day for one week. Declare two additional variables one to hold the total sum of pizzas sold...
As a volunteer at a local library, you see that library uses a system which stores...
As a volunteer at a local library, you see that library uses a system which stores member, books and other data in text files. This system was commissioned long ago, developed by one of the staff members. You are asked by the librarian to explain the limitations of file-based approach to a committee to evaluate implementation of a system that uses a database to store information.                                                  
The mean of one class is 65 and the mean of another class is 75. Explain...
The mean of one class is 65 and the mean of another class is 75. Explain the steps you would need to take to calculate a combined class average.
As at 31 March 2018, DuckTales Ltd has another financial instrument which is shares in another...
As at 31 March 2018, DuckTales Ltd has another financial instrument which is shares in another company. These shares were purchased for the purposes of making a gain on the investment. Explain to Scrooge McDuck, the CEO of Ducktakes Ltd, how the financial instrument should be accounted for at the end of each financial year. In your answer you should outline how new values for the financial instrument could and should be determined and how any change would affect the...
1. when you create a class by making it inherit from another class, the new class...
1. when you create a class by making it inherit from another class, the new class automatically, contains the data fields and _____ of the original class a. fonts b. methods c. class names d. arrays 2. if a programming language does not support ________, the language is not considered object oriented a. syntax b. applets c. loops d. polymorphism 3. when you create a class and do not provide a ______, java automatically supplies you with a default one...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT