Java Comparator和Comparabler的区别
一、 Comparable
1 public class Person implements Comparable<Person>{ 2 public int Age; 3 public String Name; 4 public int compareTo(Person o) { 5 // TODO Auto-generated method stub 6 return this.Age-o.Age; 7 } 8 } 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 Person[] persons = new Person[2];//List<Person> persons = new ArrayList<Person>(); 13 Person person1 = new Person(); 14 person1.Age = 32; 15 person1.Name = "wyp"; 16 persons[0] = person1;//persons.add(person1); 17 Person person2 = new Person(); 18 person2.Age = 12; 19 person2.Name = "lx"; 20 persons[1] = person2;//persons.add(person2); 21 22 Arrays.sort(persons);//Collections.sort(persons); 23 for (Person person : persons) { 24 String content = String.format("Name:%s,Age:%s",person.Name,person.Age); 25 System.out.println("按Age排序"); 26 System.out.println(content); 27 } 28 }
二、 Comparator
1 public class NameSort implements Comparator<Person> { 2 3 @Override 4 public int compare(Person o1, Person o2) { 5 // TODO Auto-generated method stub 6 return o1.Name.compareTo(o2.Name); 7 } 8 } 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 13 Person[] persons = new Person[2];//List<Person> persons = new ArrayList<Person>(); 14 Person person1 = new Person(); 15 person1.Age = 32; 16 person1.Name = "wyp"; 17 persons[0] = person1;//persons.add(person1); 18 Person person2 = new Person(); 19 person2.Age = 12; 20 person2.Name = "lx"; 21 persons[1] = person2;//persons.add(person2); 22 23 Arrays.sort(persons,new NameSort());//Collections.sort(persons,new NameSort()); 24 for (Person person : persons) { 25 String content = String.format("Name:%s,Age:%s",person.Name,person.Age); 26 System.out.println("按Name排序"); 27 System.out.println(content); 28 } 29 }