How do I sort an array of Person Objects by using compareto()?
Posted
by Adam
on Stack Overflow
See other posts from Stack Overflow
or by Adam
Published on 2010-04-01T03:58:51Z
Indexed on
2010/04/01
4:03 UTC
Read the original article
Hit count: 479
Here is my code:
> import java.util.Scanner;
import java.util.Arrays;
/**
This class tests the Person class.
*/
public class PersonDemo
{
public static void main(String[] args)
{
int count = 0;
Scanner in = new Scanner(System.in);
boolean more = false;
Person first = null;
Person last = null;
while (more)
{
System.out.println(
"Please enter the person's name or a blank line to quit");
String name = in.nextLine();
if (name.equals(""))
more = false;
else
{
Person p = new Person(name); //new person object created with inputted name
Person[] people = new Person[10]; //new array of 10 person objects
people[count] = p; //declare person object with index of variable count as the new person object
first = people[count]; // I have no idea what to do here. This is where I'm stuck.
last = people[count]; // I can't figure out what to do with this either.
first.compareTo(p); //call compareTo method on first and new person object
last.compareTo(p); //call compareTo method on last and new person object
count++; // increase count variable
}
}
System.out.println("First: " + first.toString());
System.out.println("Last: " + last.toString());
}
}
And the Person class:
/**
A person with a name.
*/
public class Person implements Comparable
{
/**
* Constructs a Person with a name.
* @param aName the person's name
*/
public Person(String aName)
{
name = aName;
}
public String getName()
{
return name;
}
@Override
public int compareTo(Object otherObject)
{
Person other = (Person)otherObject;
if (name.compareTo(other.name) < 0) return -1;
if (name.compareTo(other.name) > 0) return 1;
return 0;
}
/**
Returns a string representation of the object.
@return name of Person
*/
public String toString()
{
return "[name=" + name + "]";
}
private String name;
}
© Stack Overflow or respective owner