简体   繁体   English

为什么此示例中的Integer.valueOf(...)比较返回不同的值?

[英]Why do the Integer.valueOf(…) comparisons in this example return different values?

From the answer to a question about primitive types and autoboxing in java : 从答案到关于java中的原始类型和自动装箱问题

for biziclop: 对于biziclop:

class biziclop { 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 Settings\\glow\\My Documents>java biziclop false false true false C:\\Documents and Settings\\glow\\My Documents> 

Why is that? 这是为什么?

Integer.valueof caches objects for values around zero as required by the Java Language Specification. Integer.value根据Java语言规范的要求缓存对象的值为零。

Inspired by ilya's answer see the latest, actual source for Integer.valueOf() in the upcoming JDK7, lines 638-643. ilya的回答启发,请参阅即将发​​布的JDK7第638-643行中Integer.valueOf()的最新实际来源

请参阅Integer.valueOf实现: http ://docjar.com/html/api/java/lang/Integer.java.html(850s行)

You should use the equal method not the == operator. 您应该使用等于方法而不是==运算符。 == test if two objects are equal but you create different objects with same value and need the equal() method to compare the object's values. ==测试两个对象是否相等,但是您创建具有相同值的不同对象,并且需要使用equal()方法来比较对象的值。

Update: 更新:
Reason for different behavior of Integer.valouOf(5) and Integer.valouOf(500) is indeed that Integer implementation uses a static valueOfCache of size -128..127. Integer.valouOf(5)Integer.valouOf(500)不同行为的原因确实是Integer实现使用大小为-128..127的静态valueOfCache。
As of Java 7 this is configurable with the command-line argument -XX:AutoBoxCacheMax=<size> 从Java 7开始,可以使用命令行参数-XX:AutoBoxCacheMax=<size>

Integer.valueOf缓存值,特别是-128到127。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM