简体   繁体   English

爪哇| 使用泛型减少代码重复

[英]Java | Using Generics to Reduce Code Duplication

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.我一直在尝试编写一个简单但灵活的类,其中包含一些泛型类型 T 的值。T 扩展了 Number,这意味着我只想让这个类处理从字节到长整型的所有内容。 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.我尝试使用instanceof语句将它们转换为适当的包装器,但这也让我无处可去。

You can define your method like this你可以像这样定义你的方法

public static  <T extends Number> Number distanceSq(T x1,T y1,T x2,T y2){
    double x = x1.doubleValue() - x2.doubleValue();
    double y = y1.doubleValue() - y2.doubleValue();
    return (x * x + y * y);
}

And it can be called as它可以被称为

Integer r1 = distanceSq(a1, b1, a2, b2).intValue();
Byte r2 = distanceSq(x1, y1, x2, y2).byteValue();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM