100.md 6.4 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8
# Java 比较器示例

> 原文: [https://javatutorial.net/java-comparator-example](https://javatutorial.net/java-comparator-example)

在本教程中,我们将讨论 Java 比较器及其示例。

## 什么是 Java 比较器?

W
wizardforcel 已提交
9
Java `Comparator`是用于比较 Java 对象的接口。 在`java.util.comparator`包中,Java `Comparator``compare(Object 01, Object 02)`方法比较两个 Java 对象。
W
init  
wizardforcel 已提交
10

W
wizardforcel 已提交
11
通过使用可配置的方法,Java `Comparator`可以以正数、零或负数返回比较结果。 由于不限于检查数字,因此可以将 Java `Comparator`用于比较任何对象。 使用`java.io.Serializable`,可以将 Java 比较器同样用于有效地比较序列化的信息结构。
W
init  
wizardforcel 已提交
12

W
wizardforcel 已提交
13
Java `Comparator`类似于`Comparable`接口,但可用于交换排序顺序,其中`Comparable`可通过常规顺序(如字典序)进行排序。
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
## 语法
W
init  
wizardforcel 已提交
16

W
wizardforcel 已提交
17 18 19
```java
public int compare(Object obj1, Object obj2)
```
W
init  
wizardforcel 已提交
20 21 22

如何使用 Java 比较器?

W
wizardforcel 已提交
23
[`TreeSet`](https://javatutorial.net/java-treeset-example)[`TreeMap`](https://javatutorial.net/java-treemap-example) 都以自然顺序存储元素。 不管怎样,比较器明确地描述了用于排序的顺序。
W
init  
wizardforcel 已提交
24

W
wizardforcel 已提交
25
比较器接口具有两种技术的特征:`compare()``equals()`。存在`compare()`方法,专注于请求的两个组成部分:
W
init  
wizardforcel 已提交
26

W
wizardforcel 已提交
27
## `compare`方法
W
init  
wizardforcel 已提交
28 29 30

int compare(Object obj1,Object obj2)

W
wizardforcel 已提交
31
`obj1``obj2`得到比较。 如果对象相等,则此方法返回零。 如果`obj1``obj2`更大,它将返回正数。 否则返回负数。
W
init  
wizardforcel 已提交
32

W
wizardforcel 已提交
33
通过实现`compare()`,可以修改比较的方式。 例如,要按反向进行排序,可以使比较器反转比较结果。
W
init  
wizardforcel 已提交
34 35 36

![](img/5bc3e122a9704c141357fc8a272d1863.jpg)

W
wizardforcel 已提交
37
## `equals`方法
W
init  
wizardforcel 已提交
38

W
wizardforcel 已提交
39
存在`equals()`方法,用于测试对象是否与调用比较器相符 -
W
init  
wizardforcel 已提交
40

W
wizardforcel 已提交
41
`boolean equals(Object obj)`
W
init  
wizardforcel 已提交
42

W
wizardforcel 已提交
43
`obj`是检查是否相等的对象。 如果`obj`和被调用对象都是`Comparator`,并且使用类似的方法,则该方法返回真。 否则,它返回`false`
W
init  
wizardforcel 已提交
44

W
wizardforcel 已提交
45
废除`equals()`是多余的,大多数直接比较器都不会这样做。
W
init  
wizardforcel 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

## Java 比较器示例

```java
import java.util.*;

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

public class Example {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));
      Collections.sort(list);   // Sorts the array list

      for(Dog a: list)   // printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");

      for(Dog a: list)   // printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+ a.getDogAge() + ", ");
   }
}
```

```java
OUTPUT:
```

```java
Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy  : 1, Lacy  : 2, Shaggy  : 3, Tommy  : 4, Roger  : 10,
```

#### Java 比较器的工作示例。

```java
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Comparator; 

class Student { 

    // instance member variables 
    String Name; 
    int Age; 

    // parameterized constructor 
    public Student(String Name, Integer Age) { 
        this.Name = Name; 
        this.Age = Age; 
    } 

    public String getName() { 
        return Name; 
    } 

    public void setName(String Name) { 
        this.Name = Name; 
    } 

    public Integer getAge() { 
        return Age; 
    } 

    public void setAge(Integer Age) { 
        this.Age = Age; 
    } 

    // overriding toString() method 
    @Override
    public String toString() { 
        return "Customer{" + "Name=" + Name + ", Age=" + Age + '}'; 
    } 

    static class CustomerSortingComparator implements Comparator<Student> { 

        @Override
        public int compare(Student customer1, Student customer2) { 

            // for comparison 
            int NameCompare = customer1.getName().compareTo(customer2.getName()); 
            int AgeCompare = customer1.getAge().compareTo(customer2.getAge()); 

            // 2-level comparison using if-else block 
            if (NameCompare == 0) { 
                return ((AgeCompare == 0) ? NameCompare : AgeCompare); 
            } else { 
                return NameCompare; 
            } 
        } 
    } 

    public static void main(String[] args) { 

        // create ArrayList to store Student 
        List<Student> al = new ArrayList<>(); 

        // create customer objects using constructor initialization 
        Student obj1 = new Student("Ajay", 27); 
        Student obj2 = new Student("Sneha", 23); 
        Student obj3 = new Student("Simran", 37); 
        Student obj4 = new Student("Ajay", 22); 
        Student obj5 = new Student("Ajay", 29); 
        Student obj6 = new Student("Sneha", 22); 

        // add customer objects to ArrayList 
        al.add(obj1); 
        al.add(obj2); 
        al.add(obj3); 
        al.add(obj4); 
        al.add(obj5); 
        al.add(obj6); 

        // before Sorting arraylist: iterate using Iterator 
        Iterator<Student> custIterator = al.iterator(); 

        System.out.println("Before Sorting:\n"); 
        while (custIterator.hasNext()) { 
            System.out.println(custIterator.next()); 
        } 

        // sorting using Collections.sort(al, comparator); 
        Collections.sort(al, new CustomerSortingComparator()); 

        // after Sorting arraylist: iterate using enhanced for-loop 
        System.out.println("\n\nAfter Sorting:\n"); 
        for (Student customer : al) { 
            System.out.println(customer); 
        } 
    } 
}
```

W
wizardforcel 已提交
219
**输出**
W
init  
wizardforcel 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

```java
Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipu
```