本文介绍了为什么比较两个整数使用==有时工作,有时不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我正在比较参考,而我正在使用==这不是一个好主意,但我不明白为什么会发生这种情况。
I know that i am comparing reference while i'm using == which is not a good idea but i did not understand why is this happening.
Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
推荐答案
Java语言规范说包装器至少-128到127的对象被 Integer.valueOf()
缓存和重用,自动装箱会隐式使用它。
The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf()
, which is implicitly used by the autoboxing.
这篇关于为什么比较两个整数使用==有时工作,有时不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!