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());
}
我不明白为什么在第二种情况下该方法返回 Double 而不是 Integer。
最佳答案
这是因为条件表达式中使用了两种不同的类型(可转换为数值类型)作为第二个和第三个操作数。
这里解释了如何确定条件表达式的类型:http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
关于java - 方法返回 Double 而不是 Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231599/