码迷,mamicode.com
首页 > 编程语言 > 详细

JavaSE8基础 Integer 包装类对象的值不变

时间:2017-11-06 15:56:19      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:page   returns   integer   eof   img   request   不能   value   javase   

礼悟:
     好好学习多思考,尊师重道存感恩。叶见寻根三二一,江河湖海同一体。
          虚怀若谷良心主,愿行无悔给最苦。读书锻炼强身心,诚劝且行且珍惜。




       javaSE:1.8
             os:windows7 x64
            ide:MyEclipse 2017         

 

代码

package jizuiku.demo;

/**
 * Integer 包装类的对象不能改变其中的值
 * 
 * @author 给最苦
 * @version V17.11.06
 */
public class Demo {
	public static void main(String[] args) {
		// 对象引用 i 变没变?
		// 有几个Integer对象?
		Integer i = new Integer(100);

		// 这句话 没有改变 new Integer(100)所创建的对象 的值吗?
		i = i + 3;
		System.out.println(i);
	}
}

 

代码运行的结果
技术分享

 

 

为了知道 包装类对象的值不变 的原因,给最苦 对上述代码进行反编译

// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   Demo.java

package jizuiku.demo;

import java.io.PrintStream;

public class Demo
{

	public Demo()
	{
	}

	public static void main(String args[])
	{
		Integer i = new Integer(100);
		i = Integer.valueOf(i.intValue() + 3);
		System.out.println(i);
	}
}

 

  (⊙o⊙)…哪里有新对象呀?没看到new呀? 这里就有一个关键的函数 Integer.valueOf(),给最苦 查看这个函数的源代码

 

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

   关键的一句: return new Integer(i); 哦,懂了!

 


学习资源:《Head First Java》+ Xjad + 源代码 + 清净的心地。如果您有优秀的书籍,也可以推荐给 给最苦。
博文是看书后,融入思考写成的。博文好,是书写得好。博文坏,是 给最苦 没认真。

JavaSE8基础 Integer 包装类对象的值不变

标签:page   returns   integer   eof   img   request   不能   value   javase   

原文地址:http://www.cnblogs.com/jizuiku/p/7793476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!