gpt4 book ai didi

java - 使用 Java 中的比较器查找最大数组元素

转载 作者:行者123 更新时间:2023-12-01 18:15:20 25 4
gpt4 key购买 nike

所以我周二要参加算法和数据考试,但我无法从过去的论文中解决这个问题。

Write a Java static method called greatest which takes an array of objects and a Comparator object which can order objects of the array’s element type, and returns whichever element from that array is greatest according to the order given by the Comparator object. You may assume the array is of length at least 1. Your code must use no method from Java’s API except the method compare from type Comparator.Your method must be generic, so the array could have any non-primitive element type.

我的尝试:

public static void greatest(Object[] a, Comparator<Object> x) {
for (int i = 0; i < a.length; i++) {
x.compare(a[i], a[i+1]));
}
}

但正如你可能看到的,我非常无能,而且我确信我的尝试是错误的!任何帮助都会很棒。我在线查看了比较器,但它们似乎仅适用于特定数据类型,而这是适用于任何非原始元素类型的。

最佳答案

Compare<T>是一个通用接口(interface),如参数<T>所示。 T 可以是任何类。因为下面的方法采用 Comparator<T> 类型的参数,它可以采用任何实现此接口(interface)的比较器。

请注意,该数组保存 T 类型的对象。这是必要的,因为Comparator只知道如何比较这种类型的对象。

public static <T> T greatest(T[] a, Comparator<? super T> x) {
T greatest = a[0];
for (int i = 1; i < a.length; i++) {
if (x.compare(a[i], greatest) > 0) {
greatest = a[i];
}
}
return greatest;
}

关于java - 使用 Java 中的比较器查找最大数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com