zoukankan      html  css  js  c++  java
  • Int,Long比较重使用equal替换==

    首先,==有很多限制,如Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的(参考),超过范围则不行,那么使用equal则代替则完全ok

        public static void main(String[] args) {
            Long prop=4004L;
            Long prop1=4004l;
            Integer prop2=4004;
            
            Integer prop3=4004;
            if(prop2.equals(prop3)){
                System.out.println("hi");
            }else if(prop2==prop3){
                System.out.println("wrong");
            }
            
            if(prop1.equals(prop2.longValue())){
                System.out.println("helloworld");
            }else if(prop==prop1){
                System.out.println("you are wrong!");
            }

    返回结果

    hi
    helloworld

    上面的示例说明使用"=="和equal还是有不小的区别的,equal可以替代==

    Long源码如下:

        /**
         * Compares this object to the specified object.  The result is
         * <code>true</code> if and only if the argument is not
         * <code>null</code> and is a <code>Long</code> object that
         * contains the same <code>long</code> value as this object.
         *
         * @param   obj   the object to compare with.
         * @return  <code>true</code> if the objects are the same;
         *          <code>false</code> otherwise.
         */
        public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
        }

    Integer源码如下:

        /**
         * Compares this object to the specified object.  The result is
         * <code>true</code> if and only if the argument is not
         * <code>null</code> and is an <code>Integer</code> object that
         * contains the same <code>int</code> value as this object.
         *
         * @param   obj   the object to compare with.
         * @return  <code>true</code> if the objects are the same;
         *          <code>false</code> otherwise.
         */
        public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
        }
  • 相关阅读:
    C/C++字符串转换函数;
    MFC CTreeCtrl 递归遍历算法
    汉字转拼音
    Windows之权限讲解
    Ubuntu 保存文件时报E212
    ON_WM_MOUSEWHEEL无响应
    sln、db、opendb、vcxproj、filters、user文件跟踪说明
    iOS 9: UIStackView入门
    Swift语言Storyboard教程:第一部分
    springboot启动项目报错:ERROR:o.s.b.d.LoggingFailureAnalysisReporter解决办法
  • 原文地址:https://www.cnblogs.com/davidwang456/p/5870828.html
Copyright © 2011-2022 走看看