zoukankan      html  css  js  c++  java
  • Integer ==与Equals【原创】

    package Equals;
    
    public class IntegerEquals {
    
        public static void main(String[] args) {
            printLine(128);
            Integer a=128;
            Integer b=128;
            System.out.println(a==b);
            System.out.println(a.equals(b));
            
            printLine(127);
            a=127;
            b=127;
            System.out.println(a==b);
            System.out.println(a.equals(b));
            
            printLine(-128);
            a=-128;
            b=-128;
            System.out.println(a==b);
            System.out.println(a.equals(b));
            
            printLine(-129);
            a=-129;
            b=-129;
            System.out.println(a==b);
            System.out.println(a.equals(b));
        }
    
        private static void printLine(int flag) {
            System.out.println("========"+flag+"========");
        }
    
    }

    Output:

    ========128========
    false
    true
    ========127========
    true
    true
    ========-128========
    true
    true
    ========-129========
    false
    true

    原因:
    基于减少对象创建次数和节省内存的考虑,[-128,127]之间的数字会被缓存。

    [-128,127]这个范围取决于java.lang.Integer.IntegerCache.high参数的设置。

        private static class IntegerCache {
        private IntegerCache(){}
    
        static final Integer cache[] = new Integer[-(-128) + 127 + 1];
    
        static {
            for(int i = 0; i < cache.length; i++)
            cache[i] = new Integer(i - 128);
        }
        }
  • 相关阅读:
    62-函数的调用
    40-字符串类型内置方法
    47-Python进阶小结
    44-集合的内置方法
    45-数据类型分类
    43-字典类型内置方法
    42-元组类型内置方法
    41-列表类型内置方法
    es6 Reflect对象详解
    微信小程序之公共组件写法
  • 原文地址:https://www.cnblogs.com/softidea/p/4206771.html
Copyright © 2011-2022 走看看