zoukankan      html  css  js  c++  java
  • java基础面试题12--Integer--自动拆装箱

    package integer;
    
    
    public class IntegerDemo {
    
        /**
         * 创建Integer对象时,源码:Integer.valueOf(传入值)
         * 当要创建的值范围不超过-128~+127,则直接从缓冲池中获取数据
         * 
         *  “==”比较的是两个对象的引用是否相同
         * “equals”比较的是两个对象的值是否相同
         * @param args
         */
        public static void main(String[] args) {
            Integer i1 = new Integer(127);
            Integer i2 = new Integer(127);
            System.out.println(i1==i2); //false,都是new的新对象
            System.out.println(i1.equals(i2));//true,值相等
            System.out.println("----------------------------");
    
            Integer i3 = new Integer(128);
            Integer i4 = new Integer(128);
            System.out.println(i3==i4);//false,都是new的新对象
            System.out.println(i3.equals(i4));//true,值相等
            System.out.println("----------------------------");
    
            Integer i5 = 128;
            Integer i6 = 128;
            System.out.println(i5==i6);//false  两个不是同一个对象,范围超过-128~+127,创建新的对象  
            System.out.println(i5.equals(i6));//true
            System.out.println("----------------------------");
    
            Integer i7  = 127;
            Integer i8  = 127;
            System.out.println(i7==i8);//false  范围在-128~+127之间,直接从缓冲池中取,返回的是同一个对象
            System.out.println(i7.equals(i8));//true
            System.out.println("----------------------------");
    
    
    


    Integer i7 = 127;在源码中的具体实现:

    Integer i7  = Integer.valueOf(127);
    public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
                    }
    }


    通过查看源码,得出结论:
    1. 针对-128~+127之间的数据,做了一个数据缓冲池
    2. 如果数据是该池中的,则不创建新的对象,否则创建

  • 相关阅读:
    python_函数_文件
    Day_2_Python_str_list_dict的使用
    Day_1_Python_循环和格式化
    influxdb2.0版本部署+自启
    格式化Java内存工具JOL输出
    卷心菜的屯币日记
    influxDB时序数据库2.0FLUX查询语法使用记录
    两种转换2021-01-01T00:00:00Z为2021-01-01 00:00:00时间格式的方式(UTC时间转为yyyy-MM-dd HH:mm:ss)
    ThreadLocal的用处
    CentOS7使用ISO镜像文件作为离线Yum源
  • 原文地址:https://www.cnblogs.com/shiguangmanbu2016/p/5932809.html
Copyright © 2011-2022 走看看