我今天换了讲师,他说我用了一个奇怪的代码.(他说最好使用.equals,当我问为什么时,他回答"因为它是!")
所以这是一个例子:
if (o1.equals(o2))
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
而不是我习惯的:
if (o1 == o2)
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
这两者之间有什么区别.为什么他的方式(使用.equals)更好?
通过快速搜索找到了这个,但我无法理解这个答案:
请考虑以下代码段:
int i = 99999999;
byte b = 99;
short s = 9999;
Integer ii = Integer.valueOf(9); // should be within cache
System.out.println(new Integer(i) == i); // "true"
System.out.println(new Integer(b) == b); // "true"
System.out.println(new Integer(s) == s); // "true"
System.out.println(new Integer(ii) == ii); // "false"
Run Code Online (Sandbox Code Playgroud)
很明显为什么最后一行总是打印出来"false":我们正在使用==引用标识比较,而new对象永远不会是==已经存在的对象.
问题是前三行:那些比较保证在原语上int,Integer自动取消装箱?是否存在基元将被自动装箱的情况,并且执行参考标识比较?(那就是全部false!)