java - Comparator Won't Work -
public class test implements comparable <test>{ string name; int age; int salary; public test(string name, int age, int salary){ this.name = name; this.age = age; this.salary = salary; } public int compareto(test newtest){ if (this.name.compareto(newtest.name) > 0){ return 1; } else if(this.name.compareto(newtest.name) < 0){ return -1; } else{ return 0; } } public static void main(string[] args){ test albert = new test("albert", 19, 100); test james = new test("james", 16, 50); if (albert.compareto(james) == -1){ system.out.println("albert comes first"); } else if (albert.compareto(james) == 1){ system.out.println("james comes first"); } else{ system.out.println("it's tie"); } int[] testarray = new int[2]; testarray[0] = albert.age; testarray[1] = james.age; collections.sort(testarray, new testcomparator()); } }
i've created comparator called testcomparator , reason won't work collections.sort. i'm not sure why not working. ideas? tried array.sort didn't work. advice appreciated.
collections.sort()
works list<integer>
, not array.
arrays.sort()
works int[]
if want ascending order.
change array of type integer[]
, should able use version of arrays.sort()
uses comparator
.
Comments
Post a Comment