gpt4 book ai didi

java - 比较数字的通用方法

转载 作者:行者123 更新时间:2023-12-01 16:40:08 24 4
gpt4 key购买 nike

Write a method that compares 2 of any number (type restriction, class Number) and returns a positive number - if the first number is greater than the second, 0 - if the numbers are equal, a negative number - if the first number is less than the second.

这就是我尝试解决任务的方法

public class Numbers {
}
public class Comparator<T1, T2 extends Numbers>implements Comparable<BigDecimal> {
private T1 obj;
private T2 obj2;

public Comparator(T1 obj, T2 obj2) {
this.obj = obj;
this.obj2 = obj2;
}

@Override
public int compareTo() {
;
}
}

public interface Comparable<T> {
public int compareTo();
}

我对泛型和这项任务完全迷失了,有人可以解释一下这个主题吗?Numbers 类中应该包含什么?我们什么时候应该在类、方法或接口(interface)中使用泛型?我应该读什么?

谢谢

最佳答案

您可以确保这 2 个数字是数字和可比较数字。 Comparable 接口(interface)中的 compareTo 方法正是执行此操作,因此您只需调用它即可

public static <T extends Number & Comparable<? super T>> int compare(T num1, T num2) {
return num1.compareTo(num2);
}

这要求您的两个参数具有相同的类型、数字并且扩展可比较。 Comparable 具有类型参数的原因是它应该知道必须与之比较的对象的类型,而接口(interface)无法知道实现它的类的类型。

关于java - 比较数字的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61873997/

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