简体   繁体   English

方法返回Double而不是Integer

[英]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. 我不知道为什么在第二种情况下该方法返回Double而不是Integer。

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 " 当将大于“ 数组 ”大小的值传递给参数“ 索引 ”时,返回一个Double值new Double(-1)

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. 由于您的方法返回的“ Number ”类型是所有数字类的超类,因此它接受该值,并且toString()打印为十进制值。 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 您可以在Java API文档-https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html处签出Number类。

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 这里说明了如何确定条件表达式的类型: http : //docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

Take a look at the documentation for Number . 查看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. Number的子类必须提供将表示的数值转换为byte,double,float,int,long和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() . 因此,在您的情况下,如果值是int,则应使用intValue() ,对于double则应使用doubleValue()

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

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