Reinforce the Java Foundation (XV) - Java in Comparable and Comparator

1 Introduction

For objects in Java, we can only use basic operators ==,! = To determine what addresses are equal, can not be used>, <size compared. But in the actual development, we need to sort objects, that is, compare the size, it should be how to achieve it? This involves two common interface Comparable <T> Java and the Comparator <T> is achieved. Learning to use these two interfaces below by way of example.

2, Comparable Interface

Comparable is a sort based interface, which is the natural order. The interface is only one compareTo (Obj o) method for a plurality of instances of a class size comparison, thereby completing the sorting. That is a class implements the Comparable interface, it means that the class supports sorting. By implementing class overrides compareTo (Obj o) method, so that the natural order of a predetermined plurality of instances, and methods of using an array Arrays.sort or Collections.sort List object or objects to be sorted.

With String cite a simple example:

1 public class CompareTest {
2     public static void main(String[] args) {
3         String[] str=new String[]{"AA","EE","DD","CC","FF","BB"};
4         Arrays.sort(str);
5         System.out.println(Arrays.toString(str));
6     }
7 }

Operating results as follows:

It can be found after using Arrays.sort (str) to complete the order, but we did not call the compareTo (Obj o) method. We know that String implements Comparable interface source code and rewrite the interface method, when used Arrays.sort (str) indirectly called String of compareTo (Obj o) method internal sort method, so we sort of saw directly result. Like String, packaging and other implements Comparable interface, rewritten compareTo method, are clearly given way to compare two objects, you can take a look yourself compareTo method of the String source overridden. But when rewriting compareTo (Obj o) method will need to follow these three rules:

①, if the comparators (i.e., this current object) is greater than the comparators (i.e., the parameter which compareTo method), then returns a positive integer.

②, if the comparison is less than those who are being compared, it returns a negative integer.

③, if the comparison by comparators equal to, zero is returned.

Custom class can not be ordered, but then by implementing Comparable interface can be achieved, then sort by Arrays.sort or Collections.sort method. Let's look at a class of their own definition of how to use the Comparable interface to sort:

 1 public class Person  implements Comparable{
 2     private String name;
 3     private int age;
 4 
 5     public Person(String name, int age) {
 6         this.name = name;
 7         this.age = age;
 8     }
 9 
10     public String getName() {
11         return name;
12     }
13 
14     public void setName(String name) {
15         this.name = name;
16     }
17 
18     public int getAge() {
19         return age;
20     }
21 
22     public void setAge(int age) {
23         this.age = age;
24     }
25 
26     //按名字排序
27     @Override
28     public int compareTo(Object o) {
29         if(o instanceof Person){
30             Person p= (Person) o;
31             // name of type String, String directly call the compareTo here 
32              IF ( the this .name.compareTo (p.name)> 0 ) {
 33 is                  return . 1 ;
 34 is              } the else  IF ( the this .name.compareTo (p.name) < 0 ) {
 35                  return -1 ;
 36              } the else {
 37 [                  return 0 ;
 38 is              }
 39          } the else {
 40              the throw  new new a RuntimeException ( "incoming data is inconsistent ..." );
 41         }
42     }
43 
44     public static void main(String[] args) {
45         Person[] p=new Person[5];
46         p[0]=new Person("Jack",23);
47         p[1]=new Person("Marry",13);
48         p[2]=new Person("Tom",18);
49         p[3]=new Person("John",33);
50         p[4]=new Person("Thomas",41);
51         System.out.println("排序前------------");
52         for (Person person : p) {
53             System.out.print(person.getName()+":"+person.getAge()+"\n");
54         }
55         System.out.println("排序后------------");
56         Arrays.sort(p);
57         for (Person person : p) {
58             System.out.print(person.getName()+":"+person.getAge()+"\n");
59         }
60     }
61 }

Operating results as follows:

Person class implement Comparable interface and override compareTo (Obj o) method, and then we sorted by name, it can be found default sort ascending, descending if it is possible to return the value preceded by a minus sign.

3, Comparator interfaces

Comparator is a sort interface, and Comparable function is the same, but it is a custom sort. How to understand the custom sort it? If a class does not implement the Comparable interface, but the class itself is not the sort of support, then we can use Comparator to sort, or our custom class implements the Comparable interface, but a custom class code can not be changed , then you need to change the sort of way, then you can also choose to customize the sort Comparator. Comparator interface has a compare (T o1, T o2) method and compareTo (Obj o) Similarly, the sort rule is defined as:

o1> o2, the return value is a positive integer.

o1 <o2, the return value is a negative integer.

o1 = o2, the return value is zero.

String also uses a simple example:

 1 public class CompareTest {
 2     public static void main(String[] args) {
 3         String[] str=new String[]{"AA","EE","DD","CC","FF","BB"};
 4         //使用匿名内部类直接创建
 5         Arrays.sort(str, new Comparator<String>() {
 6             @Override
 7             public int compare(String o1, String o2) {
 8                 if (o1.compareTo(o2)>0){
 9                     return 1;
10                 }else if (o1.compareTo(o2)<0){
11                     return -1;
12                 }else{
13                     return 0;
14                 }
15             }
16         });
17         System.out.println(Arrays.toString(str));
18     }
19 }

We know that the interface can not be instantiated, here is the knowledge anonymous inner classes, degree of your mother may have to go find the answer.

Comparator custom classes used to sort:

 1 public class Person{
 2     private String name;
 3     private int age;
 4 
 5     public Person(String name, int age) {
 6         this.name = name;
 7         this.age = age;
 8     }
 9 
10     public String getName() {
11         return name;
12     }
13 
14     public void setName(String name) {
15         this.name = name;
16     }
17 
18     public int getAge() {
19         return age;
20     }
21 
22     public void setAge(int age) {
23         this.age = age;
24     }
25 
26     public static void main(String[] args) {
27         Person[] p=new Person[5];
28         p[0]=new Person("Jack",23);
29         p[1]=new Person("Marry",13);
30         p[2]=new Person("Tom",18);
31         p[3]=new Person("John",33);
32         p[4]=new Person("Thomas",41);
33         System.out.println("排序前------------");
34         for (Person person : p) {
35             System.out.print(person.getName()+":"+person.getAge()+"\n");
36         }
37         System.out.println("排序后------------");
38         Arrays.sort(p, new Comparator<Person>() {
39             // by age default sort, according to the name of the same age if the default sort 
40              @Override
 41 is              public  int Compare (the Person O1, O2 the Person) {
 42 is                  IF (O1 the instanceof the Person O2 && the instanceof the Person) {
 43 is                      IF (o1.age> O2 .age) {
 44 is                          return . 1 ;
 45                      } the else  IF (o1.age < o2.age) {
 46 is                          return -1 ;
 47                      } the else    {
 48                          return o1.name.compareTo (o2.name);
 49                     }
 50                  } the else {
 51 is                      the throw  new new a RuntimeException ( "incoming data is inconsistent ..." );
 52 is                  }
 53 is              }
 54 is          });
 55          for (the Person Person: P) {
 56 is              of System.out.print (person.getName ( ) + ":" + person.getAge () + "\ n-" );
 57 is          }
 58      }
 59 }

Result of the program:

This custom-sorted using a Comparator.

4. Summary

Comparable and Comparator summary of what use and differences:

①, Comparable is the java.lang package, and is under the Comparator java.util package.

②, Comparable can be seen as an internal comparator, and the comparator is an external Comparator.

③, Comparable natural ordering, Comparator is a custom order.

④, if a class does not implement the Comparable interface, but the class itself is not the sort of support, then we can use to customize Comparator sort.

Guess you like

Origin www.cnblogs.com/tang-hao-/p/11310786.html