简体   繁体   English

比较器实施

[英]Comparator Implementation

I am having a problem with understanding and using the Comparator I have been asked the following: 我在理解和使用比较器时遇到问题,有人问我以下问题:

Create a CompanyDataBase class. 创建一个CompanyDataBase类。

public java.util.ArrayList sortByName() You'll need to use a Comparator object for this. public java.util.ArrayList sortByName()为此,您将需要使用Comparator对象。

I have written this method in the class. 我已经在课堂上写了这个方法。

     @Override
   public int sortByName(Employee name1, Employee name2)
   {
      return (int) (name1.super.getName() - name2.super.getName());   
   }

And this seperate Comparator class: 这个单独的Comparator类:

import java.util.*; 导入java.util。*;

public class EmployeeNameComparator implements Comparator<Employee> 
{


   public int compare(Employee first, Employee second)
   {
      return (int) (first.super.getName() - second.super.getName());
   }

}

But I obviously wont be using the same "return (int) (name1.super.getName() - name2.super.getName());" 但是我显然不会使用相同的“返回(int)(name1.super.getName()-name2.super.getName());” line of code in both classes...but I have no idea how to implement it in the sortByName method. 这两个类中都有一行代码...但是我不知道如何在sortByName方法中实现它。

I am using a compareTo Comparator interface in a separate Employee class to invoke an overloaded use of the Comparator object. 我在单独的Employee类中使用compareTo Comparator接口来调用Comparator对象的重载使用。

Any help, suggestions, lines of code would be really appreciated!! 任何帮助,建议,代码行将不胜感激!

Strings aren't primitives and can't use subtraction. 字符串不是基元,不能使用减法。

Use the Comparable interface of strings to do this work 使用字符串的Comparable接口来完成这项工作

public int compare(Employee first, Employee second)
{
    return first.getName().compareTo(second.getName());
}

You are comparing two Strings ... so you can (if they are not null) do this: 您正在比较两个字符串...因此(如果它们不为null),您可以这样做:

name1.compareTo(name2);

Now you need to take nulls into account ... so your comparator would look something like this: 现在您需要考虑空值...,以便您的比较器看起来像这样:

public class EmployeeNameComparator implements Comparator<Employee> 
{
   public int compare(Employee first, Employee second)
   {
      if (first != null && second != null) {
           if (first.getName() != null) {
               return first.getName().compareTo(second.getName());
           }
      }
.. other cases here


   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM