简体   繁体   中英

Method return Double instead of Integer

  private Integer[] array = new Integer[]{1, 2, 3, 4};

    Number getValueByIndex(int index)
    {
        return (index >= 0 && index < array.length) ? array[index] : new Double(-1);
    }

    public static void main(String[] args)
    {
        Number value1 = new Solution().getValueByIndex(5); //-1.0, class java.lang.Double expected
        Number value2 = new Solution().getValueByIndex(2); //3, class java.lang.Integer expected

        System.out.println(value1 + ", " + value1.getClass().toString());
        System.out.println(value2 + ", " + value2.getClass().toString());
    }

I can't figure out why the method return Double instead of Integer in the second case.

Arthur, Please check this code section carefully

return (index >= 0 && index < array.length) ? array[index] : new Double(-1);

It basically translates to

Return a Double value new Double(-1) when you pass a value bigger than size of your " array " to the argument " index "

Since your method returns a " Number " type which is superclass for all number classes, it accepts the value and the toString() print as a decimal value. Hope it helps. You can checkout the Number class here at the Java API Documentation- https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html

It is because there are two different types (which are convertible to numeric types) are being used in conditional expression as the second and third operands.

How the type of a conditional expression is determined is explained here : http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

Take a look at the documentation for Number . I am quoting the relevant part here:

Subclasses of Number must provide methods to convert the represented numeric value to byte, double, float, int, long, and short.

You will definitely get odd behaviour when you don't follow what documentation says. So in your case, if the value is int, you should use intValue() , and for double use doubleValue() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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