The problem occurs when I try cast "list" as "Person[]" in order to access the compare method from the ComparePerson class.
Code:
package personlist;
import java.util.Arrays;
public class CompareTest
{
public static void main(String[] args)
{
Comparable[ ] list = new Comparable[ 5 ];
for( int p = 0; p < list.length; p++)
{
list[ p ] = new Person( (byte)(31 / (p + 1) ), "Ryan" + ( -p ), "002" + p, 185.5 + p * p );
System.out.println( list[p].toString() );
}
Arrays.sort( list );
for( Comparable P : list )
{
System.out.println( P.toString() );
}
Here>>>Arrays.sort( ( Person[] ) list, new ComparePerson() );
for( Comparable pP : list)
{
System.out.println( pP.toString() );
}
}
}
Everything runs fine up until this(main method) point, but the funny thing is no error shows up until run time. If I change the call to "list" in any way I get an error pertaining to the sort in this line
(Arrays.sort( ( Person[] ) list, new ComparePerson() );, everything else is fine.
Here is my ComparePerson class:
Code:
package personlist;
import java.util.Comparator;
public class ComparePerson implements Comparator<Person>
{
public int compare( Person p1, Person p2 )
{
if( p1 == p2)
{
return (int)p1.getHeight() - (int)p2.getHeight();
}
else
return p1.getAge() - p2.getAge();
}
}
Here is my Person class:
Code:
package personlist;
public class Person implements Comparable< Person >
{
private byte age;
private String first;
private String id;
private double height;
public double getHeight()
{
return height;
}
public String getFirst()
{
return first;
}
public byte getAge()
{
return age;
}
public String getId()
{
return id;
}
public Person()
{
}
public Person(byte age, String first, String id, double height)
{
this.age = age;
this.first = first;
this.id = id;
this.height = height;
}
public int compareTo( Person y)
{
return first.compareTo(y.first);
}
public String toString( )
{
return String.format( "%-10s%-10d%-10s%-10.2f", first, age, id, height );
}
}
The objective is to evaluate and sort the data by name, then age, and if age is equal use height as the final sorting method. I can fix this aspect of the code, but if I can't even evaluate the output, I can't fix the mechanics in the secondary evaluation of the data.
