【发布时间】:2020-08-31 05:21:28
【问题描述】:
我一直在尝试编写一个简单但灵活的类,它包含一些泛型类型 T 的值。 T 扩展了 Number,这意味着我只想让这个类处理从字节到长整型的所有内容。 我对如何使用泛型不是很熟悉,所以我向你们提出的主要问题是,是否有办法将以下一组函数缩短为一个函数,以减少不必要的代码重复。以下是给定的代码:
public static byte distanceSq(byte x1, byte y1, byte x2, byte y2) {
x1 -= x2;
y1 -= y2;
return (byte) (x1 * x1 + y1 * y1);
}
public static short distanceSq(short x1, short y1, short x2, short y2) {
x1 -= x2;
y1 -= y2;
return (short) (x1 * x1 + y1 * y1);
}
public static int distanceSq(int x1, int y1, int x2, int y2) {
x1 -= x2;
y1 -= y2;
return (int) (x1 * x1 + y1 * y1);
}
public static float distanceSq(float x1, float y1, float x2, float y2) {
x1 -= x2;
y1 -= y2;
return (float) (x1 * x1 + y1 * y1);
}
public static double distanceSq(double x1, double y1, double x2, double y2) {
x1 -= x2;
y1 -= y2;
return (double) (x1 * x1 + y1 * y1);
}
public static long distanceSq(long x1, long y1, long x2, long y2) {
x1 -= x2;
y1 -= y2;
return (long) (x1 * x1 + y1 * y1);
}
我试图写一些类似的东西:
public static <U extends Number> U distanceSq(U x1, U y1, U x2, U y2) {
x1 -= x2;
y1 -= y2;
return (x1 * x1 + y1 * y1);
}
但是,由于变量现在是对象,操作员无法解析它们。我尝试使用 instanceof 语句将它们转换为适当的包装器,但这也让我无处可去。
【问题讨论】:
-
This 可能有帮助
-
这能回答你的问题吗? How to add two java.lang.Numbers?
-
或this
-
正如链接的问题和答案所示,这在 Java 中是不可能的。这也是为什么java.lang.Math中有这么多显式方法重载的原因,它们在this OpenJdk implementation中也根据它们各自的类型显式实现了
标签: java generics code-duplication