120k views
0 votes
[Java] Using the comparable interface

The problem I'm doing is this:

Supply a class Person that implements the Comparable interface. Compare persons by their names. Ask the user to input ten names and generate ten Person objects. Using the compareTo method, determine the first and last person among them and print them.

I have created an ArrayList of the person object that stores the 10 names, but now I'm confused how to use the compareTo() method in the person class. Maybe I'm just confused by the part where it says to determine the first and the last person among them, mainly because that doesn't seem like something you would need to compare. Unless I'm supposed to iterate through the arrayList and compare the elements of the arrayList?

I have the following code for the compareTo() method:

public int compareTo(Object temp)
{
Person other = (Person) temp;

if (this.getName().equals(other.getName()))
{
return this.getName().compareTo(other.getName());
}
return 0;
}

User Xiaokun
by
4.8k points

1 Answer

6 votes

Answer:

Check the explanation

Step-by-step explanation:

public class Person implements Comparable<Person> {

private String name;

public Person(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this. name = name;

}

Override

public int compareTo(Person o) {

return name.compareTo(o.name);

}

}

Person 1 ester..) aua .

import java.util.Scanner;

public class PersonTester {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

Person[] people = new Person[10];

for (int i = 0; i < people.length; i++) {

System.out.print("Enter name of person " + (i+1) + ": ");

people[i] = new Person(in.nextLine());

}

Person first = people[0], last = people[0];

for (int i = 0; i < people.length; i++) {

if (people[i].compareTo(first) < 0) first = people[i];

if (people[i].compareTo(last) > 0) last = people[i];

}

System.out.println("First person is " + first.getName());

System.out.println("Last person is " + last.getName());

in.close();

}

}

User Egor Neliuba
by
4.6k points