双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

Integer 解析问题求解答

宅男愚智 宅男愚智 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这两天在看关于Java的面试题,看到关于Integer 的小题目,我自己动手写了一下,发现了一些问题(初学者)
问题一

源码:
> public static void main(String[] args) {
Integer f1 =100, f2 = 100, f3 = 1000, f4 = 1000;
System.out.println(f1 == f2);
System.out.println(f1 == f2);
}
正确的返回应该是:

true
false
而我的返回结果是(错误):

true
true
Integer是int的包装类,根据自动装箱/拆箱机制,两种是可以互换的。所以下面的 == 比较的不是值而是引用,通过查看Integer.java 源码发现。

调用的valueof( )

public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
valueof( )调用 IntegerCache类

> private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}
简单说数值范围在-128与127之间,数值会直接进行自动装箱/拆箱,若是超出范围,则会new 一个新Integer对象出来。所以上面的面试题中f1 == f2的结果是true,而f3 == f4的结果是false。

至于我的返回结果为什么是错误的我没有弄没有弄明白。

问题二

把问题一种的源码稍微改一下:

public static void main(String[] args) {
Integer f1 =100, f2 = 100, f3 = 1000, f4 = 1000;
System.out.println(Objects.equals(f1, f2));
System.out.println( Objects.equals(f3,f4));
}
运行结果是:

true
true
我们知道equals()类是在Object包里面,查看Object.java 可以发现:

public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
那同样,在这里Object 也是引用来,引用事也应该调用Integer.java中valueOf(int i)与IntegerCache类,为什么这里返回的是true,true?
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
宅男愚智
Java EE 67,535 成员 225,843 内容