java – 整数类对象

前端之家收集整理的这篇文章主要介绍了java – 整数类对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > Weird Integer boxing in Java                                    10个
我有一个代码片段:

  1. public class Test{
  2. public static void main(String args[]){
  3. Integer a = 100;
  4. Integer b = 100;
  5. Integer c = 5000;
  6. Integer d = 5000;
  7. System.out.println(a);
  8. System.out.println(b);
  9. System.out.println(c);
  10. System.out.println(d);
  11. if(a == b)
  12. System.out.println("a & b Both are Equal");
  13. else
  14. System.out.println("a & b are Not Equal");
  15. if(c == d)
  16. System.out.println("c & d Both are Equal");
  17. else
  18. System.out.println("c & d are Not Equal");
  19. }
  20. }

我不明白为什么输出是这样的?
输出是:
a& b两者是平等的
c& d不相等
我正在使用jdk1.7

最佳答案
这是由于虚拟机中的优化将小(常用)整数映射到重用的对象池. This answer解释了一些细节.

猜你在找的Java相关文章