SENIORITY_ORDER = new Comparator() {};"-6ren"> SENIORITY_ORDER = new Comparator() {};"-我正在学习 Java,我在 Youtube 上看到了下面的代码。我只是想知道这部分代码是如何工作的。 static final Comparator SENIORITY_ORDER = -6ren">
gpt4 book ai didi

java - 该语句如何工作 : "static final Comparator SENIORITY_ORDER = new Comparator() {};"

转载 作者:行者123 更新时间:2023-12-01 10:11:34 28 4
gpt4 key购买 nike

我正在学习 Java,我在 Youtube 上看到了下面的代码。我只是想知道这部分代码是如何工作的。

static final Comparator<Employee> SENIORITY_ORDER = 
new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e2.hireDate().compareTo(e1.hireDate());
}
};

有人可以给我解释一下吗?预先感谢您的帮助!

import java.util.*;
public class EmpSort {
static final Comparator<Employee> SENIORITY_ORDER =
new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e2.hireDate().compareTo(e1.hireDate());
}
};

// Employee database
static final Collection<Employee> employees = ... ;

public static void main(String[] args) {
List<Employee> e = new ArrayList<Employee>(employees);
Collections.sort(e, SENIORITY_ORDER);
System.out.println(e);
}
}

最佳答案

SENIORITY_ORDER Comparator(用于比较排序中的Employee)是一个 Anonymous Class 。链接的 Java 教程(部分)

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

关于java - 该语句如何工作 : "static final Comparator<Employee> SENIORITY_ORDER = new Comparator<Employee>() {};",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097937/

28 4 0