Asa*_*han 10 java comparison integer equality
可以任何机构向我解释输出中发生的事情.如果==用于比较两个ref.变量它只是检查它的引用是否相同然后输入if body,那么为什么地狱aa == bb是相等的如果creting静态方法valueOf()和ee == ff不相等(这是好的)如果创建它使用新关键字的对象?
static void main(String args[])
{
Integer aa = Integer.valueOf("12");
Integer bb = Integer.valueOf("12");
if(aa==bb)System.out.println("aa==bb");
if(aa!=bb)System.out.println("aa!=bb");
Integer ee = new Integer("12");
Integer ff = new Integer("12");
if(ee==ff)System.out.println("ee==ff");
if(ee!=ff)System.out.println("ee!=ff");
}
Run Code Online (Sandbox Code Playgroud)
输出:
AA BB ==
ee值!= FF
sic*_*ics 11
该==比较器检查对象平等的!
由于Integer.valueOf维护具有值-128到127的整数对象valueOf(String)的缓存返回缓存对象,因此==比较结果为true.
Integer a1 = new Integer("12");
Integer b1 = new Integer("12");
//a1 == b1 returns false because they point to two different Integer objects
Integer aa = Integer.valueOf("12");
Integer bb = Integer.valueOf("12");
//aa == bb returns true because they point to same cached object
Run Code Online (Sandbox Code Playgroud)
对于对象值的比较,总是使用.equals方法,对于int,long等原语,可以使用==比较器.
| 归档时间: |
|
| 查看次数: |
3497 次 |
| 最近记录: |