【问题标题】:Comparator Implementation比较器实现
【发布时间】:2014-11-22 16:20:47
【问题描述】:

我在理解和使用 Comparator 方面遇到问题,有人问我以下问题:

创建一个 CompanyDataBase 类。

public java.util.ArrayList sortByName() 您需要为此使用 Comparator 对象。

我在课堂上写过这个方法。

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

还有这个单独的 Comparator 类:

导入 java.util.*;

public class EmployeeNameComparator implements Comparator<Employee> 
{


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

}

但我显然不会使用相同的“return (int) (name1.super.getName() - name2.super.getName());”两个类中的代码行......但我不知道如何在 sortByName 方法中实现它。

我在单独的 Employee 类中使用 compareTo Comparator 接口来调用 Comparator 对象的重载使用。

任何帮助、建议、代码行将不胜感激!

【问题讨论】:

    标签: java comparator


    【解决方案1】:

    字符串不是基元,不能使用减法。

    使用字符串的 Comparable 接口来完成这项工作

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

    【讨论】:

    • 感谢您的回复。你的意思是我在 Comparator 中的方法应该是这样的:public int compare(Employee first, Employee second) { return first.super.getName().compareTo(second.super.getName()); - }
    【解决方案2】:

    你正在比较两个字符串......所以你可以(如果它们不为空)这样做:

    name1.compareTo(name2);
    

    现在您需要考虑空值...所以您的比较器看起来像这样:

    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
    
    
       }
    }
    

    【讨论】:

    • 谢谢..我将使用这种方法让我的 Comparator 覆盖所有基础..并在学习练习中尝试完全理解代码的实现(对所有事物的继承、多态性都是全新的) , 接口等等..痛苦的学习经历!!)
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2016-06-04
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多