zoukankan      html  css  js  c++  java
  • Java中 Interger的相等判断

    先看两段代码   结果你知道否?
          Integer a = 1000;
           Integer b = 1000;
           if(a == b){
            System.out.println("true");
           }else{
            System.out.println("false"); 
           }
     
     
           Integer a = 100;
           Integer b = 100;
           if(a == b){
            System.out.println("true");
           }else{
            System.out.println("false"); 
           }
     
    为什么输出结果不同呢?
     
          在Java的自动打包规范中 要求boolean 、 byte 、char  <= 127 ,介于 -128~127之间的int 和short 被包装到固定的对象中。 所以第二段代码返回true.
     
         然而,这种不确定的结果不是我们所希望的。如果在包装器对象进行比较时,调用

    equals 方法不会出现这种问题。

    public boolean equals(Object obj)

    比较此对象与指定对象。当且仅当参数不为 null,并且是一个与该对象包含相同 int 值的 Integer 对象时,结果为 true

     对于equals() 方法中当对象为 null 时,返回false.

  • 相关阅读:
    容器适配器之queue
    STL之deque
    STL之list
    STL之multiset
    STL之multimap
    STL之set
    string
    命名空间
    Windows Live Writer教程及代码高亮工具
    STL之vector
  • 原文地址:https://www.cnblogs.com/guanshun/p/5916452.html
Copyright © 2011-2022 走看看