When you do ==
you are comparing the references for equality. This means you're saying "is the address in memory the same for both Objects?"
When you do .equals()
you are comparing the Objects themselves for equality. This means you're saying "do these two Objects consider themselves equal?"
The example that was given was poor. The only caching done for these numbers that's mandated by the JLS is the .valueOf()
method. The constructor is not cached.
Furthermore, the JLS only specifies the minimum you must cache [-128:127]. JVM implementations may cache more if they so choose. This means Integer.valueOf(500) == Integer.valueOf(500)
may be false
on some machines, but true
on others.
class biziclop {
public static void main(String[] args) {
System.out.println(new Integer(5) == new Integer(5));
System.out.println(new Integer(500) == new Integer(500));
System.out.println(Integer.valueOf(5) == Integer.valueOf(5));
System.out.println(Integer.valueOf(500) == Integer.valueOf(500));
}
}
Results in:
C:Documents and SettingsglowMy Documents>java biziclop
false
false
true
false
C:Documents and SettingsglowMy Documents>
See a more detailed answer here (the comments are a gem!): Why do people still use primitive types in Java?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…