使用具有多个比较器的比较器

2024-03-17

我可以使用此代码中的所有简单比较器进行排序,但不能ComplexComparator。我不知道如何编码才能使其正常工作。任何建议/解释将不胜感激。

这是我的主要程序:

package pkgTest;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Student[] students = new Student[6];
        students[0] = new Student("Pete", 1989, 3.6);
        students[1] = new Student("Tomas", 1989, 3.9);
        students[2] = new Student("Helen", 1990, 3.6);
        students[3] = new Student("Steve", 1991, 3.7);
        students[4] = new Student("Natalie", 1993, 3.7);
        students[5] = new Student("John", 1992, 4.0);

        NameComparator byName
                = new NameComparator();
        BirthDateComparator byBirthDate
                = new BirthDateComparator();
        AverageComparator byAverage
                = new AverageComparator();

        ComplexComparator complexSorting
                = new ComplexComparator(byName,
                        byAverage);

        System.out.println("===============");
        System.out.println("Before sorting:");
        System.out.println("===============");
        for (Student student : students) {
            System.out.println(student.getName()
                    + " // " + student.getBirthDate()
                    + " // " + student.getAverage());
        }

        Arrays.sort(students, complexSorting);

        System.out.println("==============");
        System.out.println("After sorting:");
        System.out.println("==============");
        for (Student student : students) {
            System.out.println(student.getName()
                    + " // " + student.getBirthDate()
                    + " // " + student.getAverage());
        }
    }
}

以下是其余课程:

package pkgTest;

public class Student {

    private String name;
    private int birthDate;
    private double average;

    public Student(String name, int birthDate,
            double average) {
        this.name = name;
        this.birthDate = birthDate;
        this.average = average;
    }

    public String getName() {
        return this.name;
    }

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

    public int getBirthDate() {
        return this.birthDate;
    }

    public void setBirthDate(int birthDate) {
        this.birthDate = birthDate;
    }

    public double getAverage() {
        return this.average;
    }

    public void setAverage(double average) {
        this.average = average;
    }
}


package pkgTest;

import java.util.Comparator;

public class ComplexComparator implements Comparator<Student> {

    public ComplexComparator(Comparator<Student> one,
            Comparator<Student> another) {
    }

    @Override
    public int compare(Student one, Student another) {
        /*This is the part that
        I just couldn't figure
        it out to get it work.

        It has to work no matter
        which 2 of the 3 comparators
        I use to set the input
        parameters of ComplexComparator.

        I have to make it work by
        modifying only this part of
        the code.*/
    }
}


package pkgTest;

import java.util.Comparator;

public class AverageComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        if (one.getAverage()
                < another.getAverage()) {
            return -1;
        } else if (one.getAverage()
                == another.getAverage()) {
            return 0;
        } else {
            return +1;
        }
    }
}

package pkgTest;

import java.util.Comparator;

public class BirthDateComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        if (one.getBirthDate()
                < another.getBirthDate()) {
            return -1;
        } else if (one.getBirthDate()
                == another.getBirthDate()) {
            return 0;
        } else {
            return +1;
        }
    }
}


package pkgTest;

import java.util.Comparator;

public class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student one, Student another) {
        return one.getName().
                compareToIgnoreCase(another.getName());
    }
}

你必须修改类ComplexComparator就像下面这样,至少......

import java.util.Comparator;

public class ComplexComparator implements Comparator<Student> {

    private Comparator<Student> comparatorOne;
    private Comparator<Student> comparatorTwo;

    public ComplexComparator(Comparator<Student> one,
            Comparator<Student> another) {
        this.comparatorOne = one;
        this.comparatorTwo = another;
    }

    @Override
    public int compare(Student one, Student another) {
        // make a first comparison using comparator one
        int comparisonByOne = comparatorOne.compare(one, another);

        // check if it was 0 (items equal in that attribute)
        if (comparisonByOne == 0) {
            // if yes, return the result of the next comparison
            return comparatorTwo.compare(one, another);
        } else {
            // otherwise return the result of the first comparison
            return comparisonByOne;
        }
    }
}

对于两个以上Comparator你将需要一个List它们(或另一个重载的构造函数)和一个保持一定比较顺序的循环。

EDIT

对于您有关排序顺序的附加要求,这可能会有所帮助:

    public class ComplexComparator implements Comparator<Student> {

    private Comparator<Student> comparatorOne;
    private Comparator<Student> comparatorTwo;
    private boolean orderOneAscending = true;
    private boolean orderTwoAscending = true;

    /**
     * Constructor without any sort orders
     * @param one   a comparator
     * @param another   another comparator
     */
    public ComplexComparator(Comparator<Student> one, Comparator<Student> another) {
        this.comparatorOne = one;
        this.comparatorTwo = another;
    }

    /**
     * Constructor that provides the possibility of setting sort orders 
     * @param one   a comparator
     * @param orderOneAscending sort order for comparator one 
     *      (true = ascending, false = descending)
     * @param another   another comparator
     * @param orderTwoAscending sort order for comparator two
     *      (true = ascending, false = descending)
     */
    public ComplexComparator(Comparator<Student> one, boolean orderOneAscending,
            Comparator<Student> another, boolean orderTwoAscending) {
        this.comparatorOne = one;
        this.comparatorTwo = another;
        this.orderOneAscending = orderOneAscending;
        this.orderTwoAscending = orderTwoAscending;
    }

    @Override
    public int compare(Student one, Student another) {
        int comparisonByOne;
        int comparisonByAnother;

        if (orderOneAscending) {
            /*  note that your lexicographical comparison in NameComparator 
                returns a negative integer if the String is greater!
                If you take two numerical Comparators, the order will
                turn into the opposite direction! */
            comparisonByOne = comparatorOne.compare(another, one);
        } else {
            comparisonByOne = comparatorOne.compare(one, another);
        }

        if (orderTwoAscending) {
            comparisonByAnother = comparatorTwo.compare(one, another);
        } else {
            comparisonByAnother = comparatorTwo.compare(another, one);
        }

        if (comparisonByOne == 0) {
            return comparisonByAnother;
        } else {
            return comparisonByOne;
        }
    }
}

只需尝试一下这些值并尝试一些修改即可熟悉有关比较和排序的常见问题。 我希望这会有所帮助...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用具有多个比较器的比较器 的相关文章

  • java.lang.NoClassDefFoundError:HttpSessionListener

    我正在尝试部署一场我没有编写的战争 但我在日志中收到此错误 java lang NoClassDefFoundError HttpSessionListener 我知道 HttpSessionListener 位于servlet api j
  • 如何在流中收集到TreeMap中?

    我有两个Collectors groupingBy在流中 我需要收集所有信息TreeMap 我的代码 Map
  • java.sql.SQLException: ORA-01005: 给定的密码为空;登录被拒绝

    我在尝试连接到数据库时遇到以下异常 java sql SQLException ORA 01005 null password given logon denied at oracle jdbc driver T4CTTIoer proce
  • 使用 Gson 序列化时如何公开类名

    我的场景非常复杂 但总结如下 我试图了解编译器的源代码 并了解每个 AST 节点代表什么 我正在生成不同程序的 AST 的 JSON 序列化 然后检查可视化的 JSON 输出 它工作得很好 除了一个问题是在 Gson 中生成的 JSON 数
  • Jackson Json 将对象反序列化为列表

    我正在使用 Spring 的 Web 服务RestTemplate并反序列化Jackson 在来自服务器的 JSON 响应中 其中一个字段可以是对象或列表 这意味着它可以是 result or result 有没有办法通过对我要反序列化的类
  • RSA 加密-解密:BadPaddingException:数据必须以零开头

    对于一个被问了很多次的问题 我很抱歉向您询问您的技能 我有一个关于 RSA 加密的问题 我已经检查过有关此问题的其他主题 但没有找到任何有用的答案 我希望你能帮助我 我想读取一个文件 加密其内容 然后解密它并将这些解密的字节放入一个新文件中
  • 将数组中的所有值作为参数传递给函数

    我有一个值数组 a b c d 我需要将它们作为参数传递给函数 window myFunction a b c d 如果我可以将数组 对象传递到函数中 那么这会更容易 但这些函数是由其他人编写的或已经存在 我无法更改它们 它们需要作为单独的
  • 将二进制数据的 byte[] 转换为 String

    我有二进制格式的数据 hex 80 3b c8 87 0a 89 我需要将其转换为字符串 以便通过 Jackcess 将二进制数据保存在 MS Access 数据库中 我知道 我不打算在 Java 中使用 String 来存储二进制数据 但
  • (Java) 在 Mac OS X 上以编程方式访问“系统根目录”下的 SSL 证书

    我正在编写一个 Java 应用程序 它可以通过远程 Https 站点进行 REST Api 调用 远程站点由受信任的证书签名 它在 Windows 上运行良好 但由于 SSL 证书问题 在 OS X 上运行时遇到问题 我做了一些挖掘 发现原
  • 可以混合使用 JVM 语言吗?即:Groovy 和 Clojure

    我知道你可以轻松地混合groovy java clojure java 无论什么JvmLang java 这是否也意味着我也可以让 clojure 和 groovy 代码进行交互 如果我使用 Grails 或 jRoR 我也可以在该环境中使
  • 如何从对应的数组值中获取数组键?

    您可以轻松地通过其键获取数组值 如下所示 value array key 但如果我有该值并且想要它的密钥怎么办 获得它的最佳方式是什么 你可以使用array search https www php net manual en functi
  • Keycloak 社交登录 REST API

    我已经为我的 keycloak 实例启用了谷歌社交登录 但我需要将其用作休息服务 是否有可用于执行此操作的端点 Keycloak 中没有 Google 身份验证 API 但您可以使用以下方法解决它代币交换 https www keycloa
  • Spring @Value 添加验证小于

    我使用以下属性值注入 我如何向此操作添加小于验证 我的意思是我想设置一个验证user maxpassiveday可以说 财产价值不得低于 100 Value user maxpassiveday int maxpassiveday 使用Sp
  • 如何在 Ivy 中使用不同的分类器下载多个 Maven 依赖项?

    我试图依靠Neo4j 服务器 jar http repo neo4j org content repositories snapshots org neo4j app neo4j server 1 5 SNAPSHOT neo4j serv
  • 在 Java 中打开现有文件并关闭它。

    是否可以在java中打开一个文件附加数据并关闭多次 例如 psuedocode class variable declaration FileWriter writer1 new FileWriter filename fn1 writer
  • HashSet 与 LinkedHashSet

    它们之间有什么区别 我知道 LinkedHashSet 是 HashSet 的有序版本 维护一个跨所有元素的双向链接列表 使用此类代替 HashSet 当您关心迭代顺序时 当你迭代 HashSet 时 顺序是不可预测的 而 LinkedHa
  • 有时 Properties.load() 会跳过行

    在以下情况下 Properties load 会跳过 InputStream 的第二行 这是 Java 的错误还是正常行为 public class PropTest public static void main String args
  • 如何确保超类的子类方法的线程安全?

    我参加了一次面试 并被要求为以下要求设计一个课程 假设我有一个 A 类 它可以有任意数量的子类 即子类 类 A 有一个名为 doSomething 的方法 该方法是同步的 要求是 A 的所有子类都是强制性的重写 doSomething me
  • 如何正确使用Google Calendar API Events.Insert命令?

    所以我一直使用REST方法来调用Google的API 我需要将事件插入到我拥有 ID 的特定日历中 这是我发送的 POST 请求 地址 https www googleapis com calendar v3 calendars https
  • 对 Java 协议缓冲区对象进行一些小更改

    我想在 Java 协议缓冲区对象树的深处进行一个小更改 我可以使用 getBuilder 方法来创建一个新对象 该新对象是旧对象的克隆并进行一些更改 当深入完成此操作时 代码会变得丑陋 Quux Builder quuxBuilder fo

随机推荐

  • 地理编码器 grpc 失败

    上个月 地理编码器每次都开始失败 出现 grpc failed 错误 我似乎无法解决它 我看过java io IOException grpc 失败 https stackoverflow com questions 45012289 ja
  • 是否可以在设置应用程序中动态更改 iPhone 应用程序的设置页面?

    对于我正在开发的 iPhone 应用程序 我希望能够动态添加或删除应用程序设置区域的部分 理想情况下 我希望能够更改多值说明符中的选项列表 并添加可深入到一个设置页面的副本的新行 我没有在苹果文档中看到任何关于此的内容 但是编译后是否可以更
  • CSS3 - 添加类来触发动画并在完成时删除类

    我有一个 div 当我单击它时 jquery 会添加一个启动动画运行的类 当动画停止时 3 秒后 我希望删除该类 以便再次单击 div 时动画将重新开始 这只是测试 目前仅限 Chrome 浏览器 这是我的 CSS3 spin360 web
  • DataGrid 是 UWP 的替代品吗?

    我正在开发一个 UWP 应用程序 该应用程序应该在 PC 和平板电脑上使用 并在稍后的手机上使用精简版 在 PC 上 我想在两列中提供数据 在移动设备上 我打算隐藏其中一列 或者我将创建一个不同的页面 具体取决于用户的操作 我需要的功能是
  • 如何在打字稿中执行 document.getElementById().value 之类的操作?

    我有一些代码 其中包含一个反应表单 其中包含类似以下内容
  • mysql 5.7在中型sql中比mysql 5.6慢很多

    我们正在升级到 mysql 5 7 只是发现它比 5 6 版本慢得多 虽然两者具有几乎相同的配置 但 5 6 版本以毫秒为单位执行大部分 sql 而另一个版本则需要大约 1 秒或更长的时间来执行中等复杂的 sql 例如下面的 SQL Get
  • flask_sqlalchemy create_all 无需导入模型

    我想了解如何设置一个独立的脚本来调用create all无需将我的所有模型导入其中 以下是相关文件 db py from flask sqlalchemy import SQLAlchemy db SQLAlchemy test model
  • 获取 mysqldump 转储适合 psql 输入的数据(转义单引号)

    我正在尝试将数据库从 MySQL 移植到 PostgreSQL 我已经在 Postgres 中重建了架构 所以我需要做的就是获取数据 而不需要重新创建表 我可以使用迭代所有记录并一次插入一条记录的代码来完成此操作 但我尝试了这一点 但对于我
  • 默认使用哪个 Google 地图 API 版本?

    如果您不指定版本号 则使用哪个版本的 Google Maps API 也许是最新的发行版本 这有关版本控制的文档 https developers google com maps documentation javascript basic
  • Python - 释放/替换字符串变量,如何处理?

    假设我将密码以纯文本形式存储在名为的变量中passWd作为字符串 一旦我放弃这个变量 python如何释放它 例如 使用del passWd or passWd new random data 字符串是否存储为字节数组 这意味着它可以在最初
  • 类库和命名空间有什么区别?

    类库和命名空间之间的实际区别是什么 我知道两者都用于将类 命名空间等分组在一起 任何人都可以告诉我在哪种情况下应该使用类库以及何时创建新的命名空间 命名空间为类提供了概念上的分离 类库提供了物理上的分离 在 Windows 中认为是独立的
  • 导入错误:没有名为 model_selection 的模块

    我正在尝试使用train test split函数并写 from sklearn model selection import train test split 这导致 ImportError No module named model s
  • 在facet_wrap中绘制平均线

    我有以下数据集 structure list Geschaeft c 0 0961028525512254 0 0753516756309475 0 0 0722803347280335 0 0 000877706260971328 Gas
  • Pandaboard 交叉编译 Qt

    我花了几周的时间尝试为我的 Panda 板交叉编译 Qt 但没办法 我无法通过 configure 如果有人能给我帮助 我将不胜感激 我的主机系统是Ubuntu 13 04 86 64位 在Virtualbox中运行 我的目标系统是 Pan
  • Python 中的舍入是如何工作的?

    我对 Python 中舍入的工作原理有点困惑 有人能解释一下为什么Python会这样吗 Example gt gt gt round 0 05 1 this makes sense 0 1 gt gt gt round 0 15 1 thi
  • 转换文件:Android 中的 Uri 到文件

    转换的最简单方法是什么android net Uri https developer android com reference android net Uri持有一个对象file 键入一个java io File https develo
  • “在源 Y 中找不到事件 ID X 的描述。”

    我正在尝试将自定义事件从我的 Web 应用程序写入 Windows 事件日志 我没有运气让消息字符串正常工作 我不断收到 无法找到源 Y 中事件 ID X 的描述 为了缩小范围 我决定将一个事件写入我的机器上已存在的源 我只是查看了已经写出
  • Nginx 配置中静态位置的多个位置

    我的应用程序将在两个位置提供静态文件 一个是 my path project static 另一个是 my path project jsutils static 我很难让网络服务器在两个目录中查找静态内容 这是我的应用程序的 nginx
  • UICollectionView 动画(插入/删除项目)

    我想在插入和 或删除 UICollectionViewCell 时自定义动画样式 我需要这个的原因是 默认情况下 我看到插入单元格的动画具有平滑的淡入淡出效果 但是删除单元格具有向左移动 淡出动画的组合 如果不是因为一个问题 我会对此感到非
  • 使用具有多个比较器的比较器

    我可以使用此代码中的所有简单比较器进行排序 但不能ComplexComparator 我不知道如何编码才能使其正常工作 任何建议 解释将不胜感激 这是我的主要程序 package pkgTest import java util Array