我正在尝试实现一个返回给定可比较(通用)列表的最大对象的函数。
我有 3 个类,我已经实现了它们的compareTo 方法,如果它比其他类大,则返回 1;如果比其他类小,则返回 -1;如果它们相等,则返回 0。
现在我的问题是理解如何使用通用输入 COmparable 列表。
这是我的函数的签名,以及我到目前为止编写的代码(对我不起作用):
public static Comparable<?> getMax(List<Comparable<?>> ls) {
LinkedList<Comparable<?>> tmpComp = new LinkedList<Comparable<?>>();
for (Comparable<?> c : ls)
tmpComp.add(c);
Comparable<?> maxObj = tmpComp.get(0);
for (Comparable<?> c : tmpComp)
if (c.compareTo(maxObj) > 0)
m = c;
return m;
}
我正在编写一个包含用户和广告的系统。用户和广告这两个类都有“利润”字段,我在compareTo方法中所做的就是比较两个(这个或其他)中哪一个有更多的利润,然后根据该结果返回正确的值。第三类通过另一个字段进行比较,该字段也是一个 int,表示任务的级别(int)。
另外,具体来说,if 语句给我一个“不适用于参数”类型的错误。
有什么线索吗?
提前致谢!
最佳答案
阅读您的评论,我建议您重新设计模型:
interface ProfitGenerating {
double getProfit();
}
class User implements ProfitGenerating {
...
}
class Advert implements ProfitGenerating {
...
}
List<ProfitGenerating> profits = ...;
Optional<ProfitGenerating> maxProfit = profits.stream()
.max(Comparator.comparingDouble(ProfitGenerating::getProfit));
关于java - 在 3 个不同的类别上使用可比较的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50432409/