我同学京东面试, 被问到int和Integer是如何进行比较的? 他回答了intValue()函数自动装箱拆箱和Integer持有的缓存, 然后面试官说不对, 但是源码debug确实是intvalue()拆箱呀, 面试官究竟要的是什么答案呢?
我同学京东面试, 被问到int和Integer是如何进行比较的? 他回答了intValue()函数自动装箱拆箱和Integer持有的缓存, 然后面试官说不对, 但是源码debug确实是intvalue()拆箱呀, 面试官究竟要的是什么答案呢?
这个得看你的代码如何来写了。Integer.equals(int)
int == Integer
这种会把Integer
转换为int
(拆箱)进行比较,你会发现如果Integer
如果是一个null
值的时候会出现NullPointerException
。
至于面试官想要的答案,恐怕只有他自己清楚了。
话不多说:常量池
public class Test {
public static void main(String[] args) {
Integer a1 = 127;
Integer b1 = 127;
Integer a2 = 128;
Integer b2 = 128;
System.out.println(a1 == b1);
System.out.println(a2 == b2);
}
}
刚写的,你执行一下看结果
Integer.intValue()去比较值。包装类自动拆箱是不错的,在赋值,和运算的是直接可以用包装类的。但是始终是对象类型的。在使用“==”比较的时候会存在差异,楼上给出了这部分的答案。在包装类中在short范围类是可以直接比较的是没有问题的,但超出该范围就出问题。至于面试官想要的答案,只有他自己知道。
public static void main(String[] args) {
Integer a1 = 127;
Integer a2 = 127;
System.out.println(a1 == a2);// true
System.out.println(a1.equals(a2));// true
Integer b1 = 128;
Integer b2 = 128;
System.out.println(b1 == b2);// false
System.out.println(b1.equals(b2));// true
Integer c1 = 128;
int c2 = 128;
System.out.println(c1 == c2);// true
System.out.println(c1.equals(c2));// true
int d1 = 127;
Integer d2 = null;
System.out.println(d1 == d2);// NullPointerException
}
8 回答6.5k 阅读
4 回答684 阅读✓ 已解决
2 回答3.4k 阅读
3 回答1.9k 阅读✓ 已解决
1 回答2.1k 阅读✓ 已解决
1 回答2.1k 阅读✓ 已解决
1 回答960 阅读✓ 已解决
考虑-128到127之前的数字