I have been trying to write a simple but flexible class that holds some values of generic type T. T extends Number, which means I just want this class to deal with everything from bytes to longs. I am not all that familiar with how to use generics, so my main question to you guys is if there's a way to shorten the following set of functions into one function in order to reduce the unnecessary code duplication. The following is the given code:
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);
}
I have tried to write something along the lines of:
public static <U extends Number> U distanceSq(U x1, U y1, U x2, U y2) {
x1 -= x2;
y1 -= y2;
return (x1 * x1 + y1 * y1);
}
However, since the variables are objects now, the operators cannot resolve them. I tried to convert them into their appropriate wrapper using an instanceof statement, but that got me nowhere either.