Choose between overloading primitive types or using a reference to a Number object

I have confusion regarding the following parameters for a numeric method

  • Overload
int abs(int)
long abs(long)
double abs(double)
  1. Parent class reference

Abs number (number)

which approach is best and what is the difference between the two approaches?

If we use the parent class reference, no overload is needed. Is there a problem using the second style.

When should we go for the first approach and when for the second?

+4
source share
3 answers

The main difference: your option 1 works with primitive types.

While option 2 works for reference types (aka objects).

, - abs(Number). : , !

: 1 - , int, long, float, double. , , , .

2, , , , ... Number ( ).

+2

№ 2 , :

  • Number , intValue(), longValue(), doubleValue() ..
  • , , , generics, ( downcasting).

    <N extends Number> N abs(N number) {
        // choose an actual primitive type to use, e.g.: number.doubleValue()
        // TODO: create a new instance of N if number.doubleValue() is negative
    }
    

, , , .

+1

Zen ,

, . .

It also avoids the compiler creating objects, so I assume it is faster

0
source

Source: https://habr.com/ru/post/1663149/


All Articles