泛型介面之實現按name進行排序
阿新 • • 發佈:2021-01-08
1 import java.util.*; 2 public class Demo13{ 3 4 /* 5 Arrays.sort(Object[])可以對任意陣列進行排序,但待排序的元素必須實現Comparable<T>這個泛型介面 6 */ 7 8 public static void main(String[] args) throws Exception{ 9 String[] arr = {"Davi","Bob","Smith","Alice"}; 10 //因為String本身已經實現了Comparable<String>介面,所以可以直接對String陣列進行排序11 Arrays.sort(arr); 12 System.out.println(Arrays.toString(arr)); 13 14 Person[] arr2 =new Person[]{ 15 new Person("Davi",38), 16 new Person("Bob",13), 17 new Person("Smith",24), 18 new Person("Alice",35) 19}; 20 21 Arrays.sort(arr2); 22 System.out.println(Arrays.toString(arr2)); 23 } 24 } 25 26 //自定義的Person型別實現Comparable<T>介面 27 class Person implements Comparable<Person>{ 28 private String name; 29 private int age; 30 public Person(String name,intage){ 31 this.name = name; 32 this.age = age; 33 } 34 35 //重寫Comparable<Person>介面 36 @Override 37 public int compareTo(Person other){ 38 //使用String類重寫好的comparaTo(String other)方法,name首字母依據字典序列來排列元素 39 return name.compareTo(other.name); 40 } 41 42 public String toString(){ 43 return "(name:" + name + ",age:" + age + ")"; 44 } 45 46 }