toString()
compareTo()
1 import java.util.Arrays; 2 3 class Person implements Comparable<Person> { 4 String name; 5 int score; 6 Person(String name, int score) { 7 this.name = name; 8 this.score = score; 9 } 10 public String toString(){ 11 return this.name + "," + this.score; 12 } 13 @Override public int compareTo(Person other) { 14 if(this.score > other.score) return 1; 15 else if(this.score < other.score) return -1; 16 else return 0; 17 } 18 19 } 20 public class demo { 21 public static void main(String[] args) { 22 23 // String本身已经实现了Comparable<String>接口 24 // String[] ss = new String[]{"Orange", "Apple", "AAPear"}; 25 // Arrays.sort(ss); 26 // System.out.println(Arrays.toString(ss)); 27 28 Person[] ps = new Person[] { 29 new Person("Bob", 61), 30 new Person("Alice", 88), 31 new Person("Lily", 75), 32 }; 33 Arrays.sort(ps); 34 System.out.println(Arrays.toString(ps)); 35 } 36 }