Code duplication caused by primitive types: How to avoid insanity?

前端 未结 8 423
温柔的废话
温柔的废话 2020-12-13 00:44

In one of my Java projects I am plagued by code repetition due to the way Java handles (not) primitives. After having to manually copy the same change to four different loca

8条回答
  •  时光说笑
    2020-12-13 01:10

    Your question is pretty elaborate as you already seem to know all the 'good' answers. Since due to language design we are not allowed to use primitives as generic parameter types, the best practical answer is where @PeterLawrey is heading.

    public class PrimitiveGenerics {
    
        public static double genericMax( double a, double b) {
            return (a > b) ?a:b;
        }
    
    
        public int max( int a, int b) {
            return (int) genericMax(a, b);
        }
        public long max( long a, long b) {
            return (long) genericMax(a, b);
        }
        public float max( float a, float b) {
            return (float) genericMax(a, b);
        }
        public double max( double a, double b) {
            return (double) genericMax(a, b);
        }
    
    
    }
    

    The list of primitive types is small and hopefully constant in future evolution of the language and double type is the widest/most general.

    In the worst case, you compute using 64 bit variables where 32 bit would suffice. There is a performance penalty for conversion(tiny) and for pass by value into one more method (small), but no Objects are created as this is the main (and really huge) penalty for using primitive wrappers.

    I also used a static method so it is bound early and not in run-time, although it is just one and which is something that JVM optimization usually takes care of but it won't hurt anyway. May depend on real case scenario.

    Would be lovely if someone tested it, but I believe this is the best solution.

    UPDATE: Based on @thkala's comment, double may only represent long-s until certain magnitude as it loses precision (becomes imprecise when dealing with long-s) after that:

    public class Asdf2 {
    
        public static void main(String[] args) {
            System.out.println(Double.MAX_VALUE); //1.7976931348623157E308
            System.out.println( Long.MAX_VALUE); //9223372036854775807
            System.out.println((double) Long.MAX_VALUE); //9.223372036854776E18
        }
    }
    

提交回复
热议问题