Question: public class Person implements Comparable { // private data fields private int age; private String name; private String eyeColor; // constructor // parameters in order

public class Person implements Comparable { // private data fields private int age; private String name; private String eyeColor; // constructor // parameters in order are: age, name, and eye color public Person(int a, String n, String ec) { age = a; name = n; eyeColor = ec; } // accessor methods public int getAge() { return age; } public String getName() { return name; } public String getEyeColor() { return eyeColor; } // toString method public String toString() { return age + " " + name + " " + eyeColor; } // implementation of the compareTo method // comparison is based first on age, and then on name // returns a negative number if this object is "less than" the parameter // returns a positive number if this object is "greater than" the parameter // returns a 0 if this object is "equal to" the parameter public int compareTo(Object other) { Person o = (Person)other; if (age < o.getAge()) return -1; else if (age > o.getAge()) return +1; else // age is the same, so secondarily compare names // just use the return value from Strings compareto method return name.compareTo(o.getName()); } }

The provided Person class implements the Comparable interface meaning that the Person class has a compareTo() method which returns an integer indicating whether the Person object is less than, equal to, or greater than the provided Person object.

Create a driver that asks the user how many people they would like to enter. Create an array of Person objects of that size. Have the user "create" each person by entering all data fields.

After the last Person is entered, output the array in unsorted order. Perform an insertion sort which uses Person's compareTo method. Output your sorted array and verify that the elements are in ascending order.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!