Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何正确使用Java comparator?_Java_Oop_Sorting_Comparator - Fatal编程技术网

如何正确使用Java comparator?

如何正确使用Java comparator?,java,oop,sorting,comparator,Java,Oop,Sorting,Comparator,如果我有以下课程: public class Employee { private int empId; private String name; private int age; public Employee(int empId, String name, int age) { // set values on attributes } // getters & setters } 如何使用按姓名、年龄、身份进行比较

如果我有以下课程:

public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}

如何使用按姓名、年龄、身份进行比较的比较器?

更新

刚才遇到了这个问题:其中一个链接的答案将依次调用多个比较器,直到从比较器接收到非零结果,或者调用所有比较器。这可能是您首选的解决方案


也许
Comparator#compare()
的这一(未经测试的)实现会起到作用

int compare(Employee e, Employee f)
{
    int val = e.name.compareTo(f.name);

    if(val == 0)
    {
        val = e.age - f.age;

        if(val == 0)
        {
            val = e.empId - f.empId;
        }
    }

    return val;
}

您需要实现它,以便它按首选元素排序。也就是说,您需要按姓名进行比较,如果该比较相等,则按年龄进行比较。下面列出了一个示例:

public class EmployeeComparator implements Comparator<Employee> {

  @Override
  public int compare(Employee e1, Employee e2) {
    int nameDiff = e1.getName().compareTo(e2.getName());

    if(nameDiff != 0) {
      return nameDiff;
    }

    int ageDiff = e1.getAge() - e2.getAge();

    if(ageDiff != 0) {
      return ageDiff;
    }

    int idDiff = e1.getEmpId() - e2.getEmpId();

    return idDiff;
  }
}
公共类EmployeeComparator实现Comparator{
@凌驾
公共整数比较(员工e1、员工e2){
int-nameDiff=e1.getName().compareTo(e2.getName());
如果(nameDiff!=0){
返回nameDiff;
}
int-ageDiff=e1.getAge()-e2.getAge();
如果(ageDiff!=0){
返回年龄差异;
}
int-idDiff=e1.getEmpId()-e2.getEmpId();
返回idDiff;
}
}

您还可以在类中实现类似的接口

例如,类似这样的内容:

public class Employee implements Comparable<Employee>{
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
            // set values on attributes

    }
    // getters & setters

    public int compareTo(Employee o) {
        int ret = this.name.compareTo(o.name);
        if(ret == 0)
            ret = this.age - o.age;
        if(ret == 0)
            ret = this.empId - o.empId;

        return ret;
    }
}
public类Employee实现了可比较的{
私有内部empId;
私有字符串名称;
私人互联网;
公共雇员(int-empId、字符串名称、int-age){
//在属性上设置值
}
//接球手和接球手
公共内部比较(员工o){
int ret=this.name.compareTo(o.name);
如果(ret==0)
ret=此年龄-o年龄;
如果(ret==0)
ret=this.empId-o.empId;
返回ret;
}
}
因此,您不必实现额外的类来比较您的员工。

实现它

public class Employee {
    private int empId;
    private String name;
    private int age;
    /**
     * @param empId
     * @param name
     * @param age
     */
    public Employee(int empId, String name, int age) {
        super();
        this.empId = empId;
        this.name  = name;
        this.age   = age;
    }
    /**
     * 
     */
    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }


    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    //Compare by name, age and then id
    public static Comparator<Employee> COMPARE_EMPLOYEE = new Comparator<Employee>() {
        public int compare(Employee one, Employee other) {
            //Compare Name
            if (one.getName().compareToIgnoreCase(other.getName()) == 0) {
                //Compare age
                if((one.getAge() - other.getAge()) == 0) {
                    // Now check with id is useless
                    // So directly return result of compare by id
                    return one.getEmpId() - other.getEmpId();
                } else { //If age Not equal
                    return one.getAge() - other.getAge();
                }
            } else { //If name not equal
                return one.getName().compareToIgnoreCase(other.getName());
            }
        }
    };
}
公共类员工{
私有内部empId;
私有字符串名称;
私人互联网;
/**
*@param empId
*@param name
*@param年龄
*/
公共雇员(int-empId、字符串名称、int-age){
超级();
this.empId=empId;
this.name=名称;
这个。年龄=年龄;
}
/**
* 
*/
公职人员(){
超级();
//TODO自动生成的构造函数存根
}
public int getEmpId(){
返回empId;
}
公共无效setEmpId(int-empId){
this.empId=empId;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共整数getAge(){
回归年龄;
}
公共无效设置(整数){
这个。年龄=年龄;
}
//按姓名、年龄和id进行比较
公共静态比较器COMPARE\u EMPLOYEE=新比较器(){
公共整数比较(员工一,员工另一){
//比较名称
if(一个.getName().compareToIgnoreCase(另一个.getName())==0){
//比较年龄
if((一个.getAge()-另一个.getAge())==0){
//现在用id检查是没有用的
//所以直接返回通过id进行比较的结果
返回一个.getEmpId()-other.getEmpId();
}否则{//如果年龄不相等
返回一个.getAge()-other.getAge();
}
}else{//如果名称不相等
返回一个.getName().compareToIgnoreCase(其他.getName());
}
}
};
}
使用:

List<Employee> contacts = new ArrayList<Employee>();
//Fill it.

//Sort by address.
Collections.sort(contacts, Employee.COMPARE_EMPLOYEE);
List contacts=new ArrayList();
//填满它。
//按地址排序。
集合。排序(联系人、员工、比较员工);
阅读,这一定会帮助你,你会得到更多的想法和不同类型的比较器的使用

番石榴:

List List=new ArrayList();
//...
Collections.sort(list,new Comparator(){
@凌驾
公共整数比较(员工e1、员工e2){
返回ComparisonChain.start()
.比较(e1.empId,e2.empId)
.比较(e1.name,e2.name)
.比较(e1.age,e2.age).result();
}});
使用以下方法:

public class Test 
{
    public static void main(String[] args) 
    {
        Employee emp1 = new Employee(2, "Tom", 20);
        Employee emp2 = new Employee(1, "Tom", 20);
        Employee emp3 = new Employee(3, "Hank", 21);

        List<Employee> list = new ArrayList<>();

        list.add(emp1);
        list.add(emp2);
        list.add(emp3);

        Collections.sort(list, new Employee().new MyComparator());

        System.out.println(list);
    }
}

class Employee 
{
    private int empId;
    private String name;
    private int age;

    public Employee()
    {}

    public Employee(int empId, String name, int age) 
    {
        this.empId = empId;
        this.name = name;
        this.age = age;
    }

    class MyComparator implements Comparator<Employee>
    {
        @Override
        public int compare(Employee e1, Employee e2) 
        {
            if(e1.name.compareTo(e2.name) == 0)
            {
                if(((Integer)e1.age).compareTo(e2.age) == 0)
                {
                    return ((Integer)e1.empId).compareTo(e2.empId);
                }
                else
                {
                    return ((Integer)e1.age).compareTo(e2.age);
                }
            }
            return e1.name.compareTo(e2.name);
        }
    }

    @Override
    public String toString() 
    {
        return "Employee [empId=" + empId + ", name=" + name + ", age=" + age + "]";
    }
}
公共类测试
{
公共静态void main(字符串[]args)
{
员工emp1=新员工(2,“汤姆”,20);
员工emp2=新员工(1,“汤姆”,20);
员工emp3=新员工(3,“Hank”,21);
列表=新的ArrayList();
添加列表(emp1);
列表。添加(emp2);
列表。添加(emp3);
Collections.sort(list,new Employee().new MyComparator());
系统输出打印项次(列表);
}
}
班级员工
{
私有内部empId;
私有字符串名称;
私人互联网;
公职人员()
{}
公共雇员(int-empId、字符串名称、int-age)
{
this.empId=empId;
this.name=名称;
这个。年龄=年龄;
}
类MyComparator实现比较器
{
@凌驾
公共整数比较(员工e1、员工e2)
{
if(e1.name.compareTo(e2.name)==0)
{
if(((整数)e1.age).compareTo(e2.age)==0)
{
返回((整数)e1.empId).compareTo(e2.empId);
}
其他的
{
返回((整数)e1.age).compareTo(e2.age);
}
}
返回e1.name.compareTo(e2.name);
}
}
@凌驾
公共字符串toString()
{
return“Employee[empId=“+empId+”,name=“+name+”,age=“+age+””;
}
}

比较器接口定义了两种方法:
compare()
equals()

compare()
方法比较两个元素的顺序:
int比较(对象obj1,对象obj2)

obj1
obj2
是要比较的对象。如果对象相等,此方法返回零。如果obj1大于obj2,则返回正值。O
public class Test 
{
    public static void main(String[] args) 
    {
        Employee emp1 = new Employee(2, "Tom", 20);
        Employee emp2 = new Employee(1, "Tom", 20);
        Employee emp3 = new Employee(3, "Hank", 21);

        List<Employee> list = new ArrayList<>();

        list.add(emp1);
        list.add(emp2);
        list.add(emp3);

        Collections.sort(list, new Employee().new MyComparator());

        System.out.println(list);
    }
}

class Employee 
{
    private int empId;
    private String name;
    private int age;

    public Employee()
    {}

    public Employee(int empId, String name, int age) 
    {
        this.empId = empId;
        this.name = name;
        this.age = age;
    }

    class MyComparator implements Comparator<Employee>
    {
        @Override
        public int compare(Employee e1, Employee e2) 
        {
            if(e1.name.compareTo(e2.name) == 0)
            {
                if(((Integer)e1.age).compareTo(e2.age) == 0)
                {
                    return ((Integer)e1.empId).compareTo(e2.empId);
                }
                else
                {
                    return ((Integer)e1.age).compareTo(e2.age);
                }
            }
            return e1.name.compareTo(e2.name);
        }
    }

    @Override
    public String toString() 
    {
        return "Employee [empId=" + empId + ", name=" + name + ", age=" + age + "]";
    }
}
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() + ", ");
   }
}