ParseInt()与valueof()的区别

<div id="body">
    <div class="container">
        <div class="row" style="display: block;">    
    


<div class="col-mb-12 col-8" id="main" role="main">
    <article class="post" itemscope="" itemtype="http://schema.org/BlogPosting">
        <h1 class="post-title" itemprop="name headline"><a itemtype="url" href="http://10176523.cn/archives/52/">浅谈java中parseInt和valueOf的区别</a></h1>
        <ul class="post-meta">
            <li itemprop="author" itemscope="" itemtype="http://schema.org/Person">作者: <a itemprop="name" href="http://10176523.cn/author/1/" rel="author">darren</a></li>
            <li>时间: <time datetime="2015-12-24T19:24:00+08:00" itemprop="datePublished">2015-12-24</time></li>
            <li>分类: <a href="http://10176523.cn/category/coding/">coding</a></li>
        </ul>
        <div class="post-content" itemprop="articleBody">
            <p>最近带新人,遇到一个java中很常用的问题,java中转int时<strong><code>Integer.parseInt</code></strong>和<strong><code>Integer.valueOf</code></strong>的有何区别。这种题目应该算是java基础面试题的一种啦(不过貌似也应该不会有那个无聊D疼得面试官再考这种题了)。</p>
<!--more-->
<p>查看java API文档以及源码</p>
<div class="d_hl"><i class="d_hl_sl">public</i> <i class="d_hl_sl">static</i> <i class="d_hl_sl">Integer</i> <i class="d_hl_sl">valueOf(String</i> <i class="d_hl_sl">s)</i> <i class="d_hl_sl">throws</i> <i class="d_hl_sl">NumberFormatException</i> {<br>&nbsp; &nbsp; return Integer.valueOf(parseInt(s, 10));<br>}</div>
<p>可以看出valueOf实际上就是将字符串参数作为有符号的十进制整数进行分析。</p>
<p>而看<strong><code>Integer.valueOf(int)</code></strong> 的文档说,返回一个整数,表示指定的int值的实例。如果一个新的整数的实例是不需要的,这种方法一般应优先使用构造函数整型(int),这种方法可能会产生显着更好的空间和时间,通过缓存经常请求的价值表现。该方法将在-128到127之间内缓存值,包括在内,并可以缓存在这个范围之外的其他值。</p>
<p>而且自己写了一个简单的测试</p>
<div class="d_hl">System.out.println(Integer.parseInt(<i class="d_hl_st">"100"</i>)==Integer.parseInt(<i class="d_hl_st">"100"</i>));<br>System.out.println(Integer.valueOf(<i class="d_hl_st">"100"</i>)==Integer.valueOf(<i class="d_hl_st">"100"</i>));<br>System.out.println(Integer.valueOf(100)==Integer.valueOf(100));<br>System.out.println(Integer.parseInt(<i class="d_hl_st">"100"</i>)==Integer.valueOf(<i class="d_hl_st">"100"</i>));<br>System.out.println(Integer.parseInt(<i class="d_hl_st">"100"</i>)==Integer.valueOf(100));<br>System.out.println(Integer.valueOf(<i class="d_hl_st">"100"</i>)==Integer.valueOf(100));<br>System.out.println(<i class="d_hl_st">"==================="</i>);<br>System.out.println(Integer.parseInt(<i class="d_hl_st">"500"</i>)==Integer.parseInt(<i class="d_hl_st">"500"</i>));<br>System.out.println(Integer.valueOf(<i class="d_hl_st">"500"</i>)==Integer.valueOf(<i class="d_hl_st">"500"</i>));<br>System.out.println(Integer.valueOf(500)==Integer.valueOf(500));<br>System.out.println(Integer.parseInt(<i class="d_hl_st">"500"</i>)==Integer.valueOf(<i class="d_hl_st">"500"</i>));<br>System.out.println(Integer.parseInt(<i class="d_hl_st">"500"</i>)==Integer.valueOf(500));<br>System.out.println(Integer.valueOf(<i class="d_hl_st">"500"</i>)==Integer.valueOf(500));</div>
<p>测试后的结果为:</p>
<div class="d_hl"><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br>===================<br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">false</i><br><i class="d_hl_kw">false</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">true</i><br><i class="d_hl_kw">false</i></div>
<p>原谅我这么简单粗暴。<br>
不难理解,在小于128的时候<strong><code>parseInt</code></strong>的返回原始的<code>int</code>类型,而<strong><code>valueOf</code></strong>返回系统缓存的值,所以前面都是<code>true</code>,但当大于128时 <strong><code>parseInt</code></strong> 的返回值仍然是基本类型<code>int</code>,但<strong><code>valueOf</code></strong> 会创建一个<code>Integer</code>的封装类型并返回,使用<code>==</code>符号来判断的时候封装类型对比的是内存地址,但是java中基本类型又自动封装和拆箱的功能,基本类型和封装类型使用<code>==</code>号作比较的时候会将封装类型自动拆箱,所有如果使用<strong><code>parseInt</code></strong>和<strong><code>valueOf</code></strong> 做<strong><code>==</code></strong>比较时会自动将<strong><code>valueOf</code></strong>返回的<code>Integer</code>封装类型<em><code>自动拆箱</code></em>,判断两个<code>int</code>因而返回<code>true</code>,但后面的只要出现两个<strong><code>valueOf</code></strong>,判断的都是封装类型,所以就是<code>false</code>!!</p>
<p>比如<strong><code>System.out.println(new Integer(1)==new Integer(1));</code></strong> 因为是<code>new</code>的两个<code>Integer</code>封装对象,所以比较的是内存地址,返回值为<code>false</code>。</p>
<p>总结一下就是:</p>
<table>
    <tbody><tr>
        <td colspan="3">128以内(不包括128)</td>
    </tr>
    <tr>
        <td>int == int</td><td>true</td><td>值对比</td>
    </tr>
    <tr>
        <td>int == Integer</td><td>ture</td><td>自动将Integer拆箱为int再做值对比</td>
    </tr>
    <tr>
        <td>Integer == Integer</td><td>ture</td><td>Integer 为直接赋值,128以内为系统缓存</td>
    </tr>
    <tr>
        <td>new Integer == new Integer</td><td>false</td><td>任意某个Integer为new Integer创建</td>
    </tr>
    <tr>
        <td colspan="3">128及以上(包括128)</td>
    </tr>
    <tr>
        <td>int == int</td><td>true</td><td>值对比</td>
    </tr>
    <tr>
        <td>int == Integer</td><td>ture</td><td>自动将Integer拆箱为int再做值对比</td>
    </tr>
    <tr>
        <td>Integer ==Integer</td><td>false</td><td>比较内存地址</td>
    </tr>
</tbody></table>
            <hr>
<div id="post_copyright" data-url="http://10176523.cn/archives/52/">本文地址:<a title="浅谈java中parseInt和valueOf的区别 - darren's blog" href="http://10176523.cn/archives/52/">http://10176523.cn/archives/52/</a></div>
<br>
<a href="https://portal.qiniu.com/signup?code=3lplkanhnb9zm" style="color:#336633">如果我的文章对你有帮助,不妨也帮助我,请点击这段文字,打开页面注册一个七牛账号,让我能获得更多的流量!</a>


<hr>
<p>相关文章:</p>
    <ul>
        <li><a href="http://10176523.cn/archives/75/" title="HTML5的电池状态api">HTML5的电池状态api</a></li>
        <li><a href="http://10176523.cn/archives/67/" title="iText使用HTML生成PDF设置重复表头和强制翻页">iText使用HTML生成PDF设置重复表头和强制翻页</a></li>
        <li><a href="http://10176523.cn/archives/66/" title="java8新日期API的LocalDate和传统Date类型的互相转换">java8新日期API的LocalDate和传统Date类型的互相转换</a></li>
        <li><a href="http://10176523.cn/archives/55/" title="Java 8 时间日期库的20个使用示例">Java 8 时间日期库的20个使用示例</a></li>
        <li><a href="http://10176523.cn/archives/53/" title="java自定义将10进制转62进制">java自定义将10进制转62进制</a></li>
    </ul>        </div>
        <p itemprop="keywords" class="tags">标签: <a href="http://10176523.cn/tag/java/">java</a>, <a href="http://10176523.cn/tag/%E5%8E%9F%E5%88%9B/">原创</a></p>
    </article>


    <div id="comments">
        
        <div id="respond-post-52" class="respond">
        <div class="cancel-comment-reply">
        <a id="cancel-comment-reply-link" href="http://10176523.cn/archives/52/#respond-post-52" rel="nofollow" style="display:none" οnclick="return TypechoComment.cancelReply();">取消回复</a>        </div>
    
    <h3 id="response">添加新评论</h3>
    <form method="post" action="http://10176523.cn/archives/52/comment" id="comment-form" role="form">
                        <p>
                <label for="qq">QQ</label>
                <input type="text" id="qq" class="text" pattern="[0-9]*" maxlength="11" οnblur="var d,h,_val,tag,qq=this.value;qq.length>0&amp;&amp;(/^[1-9]\d{4,10}$/.test(qq)?(d=document,h=d.getElementsByTagName('head')[0],_val=function(a,b){return d.getElementById(a).value=b},tag=d.createElement('script'),window.portraitCallBack=function(a){_val('author',a[qq][6]),_val('mail',qq+'@qq.com'),_val('url','http://user.qzone.qq.com/'+qq),window.portraitCallBack=null},tag.οnlοad=tag.οnerrοr=function(){h.removeChild(tag)},tag.onreadystatechange=function(){/loaded|complete/i.test(tag.readyState)&amp;&amp;h.removeChild(tag)},tag.async=!0,tag.charset='GBK',tag.type='text/javascript',tag.src='http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?get_nick=1&amp;uins='+qq,h.appendChild(tag)):(this.value='',alert('您输入的QQ号有误!')));" placeholder="使用QQ号自动填充资料">
            </p>
    <p>
                <label for="author" class="required">称呼</label>
    <input type="text" name="author" id="author" class="text" value="" required="">
    </p>
    <p>
                <label for="mail" class="required">Email</label>
    <input type="email" name="mail" id="mail" class="text" value="" required="">
    </p>
    <p>
                <label for="url">网站</label>
    <input type="url" name="url" id="url" class="text" placeholder="http://" value="">
    </p>
                <p>
                <label for="textarea" class="required">内容</label>
                <textarea rows="8" cols="50" name="text" id="textarea" class="textarea" required=""></textarea>
            </p>
    <p>
                <button type="submit" class="submit">提交评论</button>
            </p>
    </form>
    </div>
<script type="text/javascript">
(function () {
    window.TypechoComment = {
        dom : function (id) {
            return document.getElementById(id);
        },
    
        create : function (tag, attr) {
            var el = document.createElement(tag);
        
            for (var key in attr) {
                el.setAttribute(key, attr[key]);
            }
        
            return el;
        },


        reply : function (cid, coid) {
            var comment = this.dom(cid), parent = comment.parentNode,
                response = this.dom('respond-post-52'), input = this.dom('comment-parent'),
                form = 'form' == response.tagName ? response : response.getElementsByTagName('form')[0],
                textarea = response.getElementsByTagName('textarea')[0];


            if (null == input) {
                input = this.create('input', {
                    'type' : 'hidden',
                    'name' : 'parent',
                    'id'   : 'comment-parent'
                });


                form.appendChild(input);
            }


            input.setAttribute('value', coid);


            if (null == this.dom('comment-form-place-holder')) {
                var holder = this.create('div', {
                    'id' : 'comment-form-place-holder'
                });


                response.parentNode.insertBefore(holder, response);
            }


            comment.appendChild(response);
            this.dom('cancel-comment-reply-link').style.display = '';


            if (null != textarea && 'text' == textarea.name) {
                textarea.focus();
            }


            return false;
        },


        cancelReply : function () {
            var response = this.dom('respond-post-52'),
            holder = this.dom('comment-form-place-holder'), input = this.dom('comment-parent');


            if (null != input) {
                input.parentNode.removeChild(input);
            }


            if (null == holder) {
                return true;
            }


            this.dom('cancel-comment-reply-link').style.display = 'none';
            holder.parentNode.insertBefore(response, holder);
            return false;
        }
    };
})();
</script>
<script type="text/javascript">
(function () {
    var event = document.addEventListener ? {
        add: 'addEventListener',
        focus: 'focus'
    } : {
        add: 'attachEvent',
        focus: 'onfocus'
    };


    !function(){
        var r = document.getElementById('respond-post-52');
        if (null != r) {
            var forms = r.getElementsByTagName('form');
            if (forms.length > 0) {
                var f = forms[0], textarea = f.getElementsByTagName('textarea')[0], added = false;
                if (null != textarea && 'text' == textarea.name) {
                    textarea[event.add](event.focus, function () {
                        if (!added) {
                            var input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = '_';
                            input.value = (function () {
    var _Agbvp = 'Fc'//'Fc'
+'7'//'sk'
+'62'//'jz'
+'78'//'N'
+//'Llq'
'1'+'4cc'//'v'
+/* 'fQ'//'fQ' */''+'ae5'//'S'
+//'T'
'0'+//'h'
'd'+'7'//'2YU'
+//'e'
'5d4'+'yy'//'yy'
+/* 'N1'//'N1' */''+//'GQ0'
'373'+//'SrS'
'fc2'+'ef'//'ef'
+''///*'JBd'*/'JBd'
+''///*'J'*/'J'
+//'5CM'
'0f8'+//'Uc'
'f'+//'Z4'
'b'+'0a8'//'18'
, _5ol1 = [[0,2],[18,20],[24,26]];
    
    for (var i = 0; i < _5ol1.length; i ++) {
        _Agbvp = _Agbvp.substring(0, _5ol1[i][0]) + _Agbvp.substring(_5ol1[i][1]);
    }


    return _Agbvp;
})();
                            f.appendChild(input);
                            added = true;
                        }
                    });
                }
            }
        }
    }()
})();
</script>    </div>


    <ul class="post-near">
        <li>上一篇: <a href="http://10176523.cn/archives/51/" title="osx下快速复制文件/文件夹的路径">osx下快速复制文件/文件夹的路径</a></li>
        <li>下一篇: <a href="http://10176523.cn/archives/53/" title="java自定义将10进制转62进制">java自定义将10进制转62进制</a></li>
    </ul>
</div><!-- end #main-->
<div class="col-mb-12 col-offset-1 col-3 kit-hidden-tb" id="secondary" role="complementary">
        <section class="widget">
<h3 class="widget-title">最新文章</h3>
        <ul class="widget-list">
            <li><a href="http://10176523.cn/archives/75/">HTML5的电池状态api</a></li><li><a href="http://10176523.cn/archives/68/">sublime text集成nodejs(附解析虾米和网易云音乐地址)</a></li><li><a href="http://10176523.cn/archives/67/">iText使用HTML生成PDF设置重复表头和强制翻页</a></li><li><a href="http://10176523.cn/archives/66/">java8新日期API的LocalDate和传统Date类型的互相转换</a></li><li><a href="http://10176523.cn/archives/65/">强迫症的福音,删除OSX的软件安装记录</a></li><li><a href="http://10176523.cn/archives/62/">OSX上不借助第三方工具直接读写NTFS硬盘格式</a></li><li><a href="http://10176523.cn/archives/57/">osx上快速的新建一个unix可执行文件</a></li><li><a href="http://10176523.cn/archives/56/">新年换新装,Mac OSX之图标修改</a></li><li><a href="http://10176523.cn/archives/55/">Java 8 时间日期库的20个使用示例</a></li><li><a href="http://10176523.cn/archives/54/">HTML中的那些空格</a></li>        </ul>
    </section>
    
        <section class="widget">
<h3 class="widget-title">最近回复</h3>
        <ul class="widget-list">
                            <li><a href="http://10176523.cn/archives/29/comment-page-1#comment-56">Siben</a>: 对了,我新版本的office 是15.19.1。旧版本直接删除到...</li>
                    <li><a href="http://10176523.cn/archives/29/comment-page-1#comment-55">Siben</a>: 试了其他诸多网帖,没有一个成功的。楼主这篇帖子,步骤简单,分类明...</li>
                    <li><a href="http://10176523.cn/archives/29/comment-page-1#comment-54">violin</a>: 我用的是15.19.1版本
</li>
                    <li><a href="http://10176523.cn/archives/29/comment-page-1#comment-53">violin</a>: 感谢博主,参考其他网站装了好几次,都未成功,看了博主的文章才知道...</li>
                    <li><a href="http://10176523.cn/about.html/comment-page-1#comment-52">Tal</a>: 有兴趣认识下吗,我也是个有摇滚心的孩子。数学、哲学爱好者
微信q...</li>
                </ul>
    </section>
    
        <section class="widget">
<h3 class="widget-title">分类</h3>
        <ul class="widget-list"><li class="category-level-0 category-parent"><a href="http://10176523.cn/category/default/">default</a></li><li class="category-level-0 category-parent"><a href="http://10176523.cn/category/coding/">coding</a></li><li class="category-level-0 category-parent"><a href="http://10176523.cn/category/apple/">osx</a></li><li class="category-level-0 category-parent"><a href="http://10176523.cn/category/crack/">crack</a></li></ul> </section>
    
        <section class="widget">
<h3 class="widget-title">归档</h3>
        <ul class="widget-list">
            <li><a href="http://10176523.cn/2016/04/">2016年04月</a></li><li><a href="http://10176523.cn/2016/03/">2016年03月</a></li><li><a href="http://10176523.cn/2016/02/">2016年02月</a></li><li><a href="http://10176523.cn/2016/01/">2016年01月</a></li><li><a href="http://10176523.cn/2015/12/">2015年12月</a></li><li><a href="http://10176523.cn/2015/11/">2015年11月</a></li><li><a href="http://10176523.cn/2015/10/">2015年10月</a></li><li><a href="http://10176523.cn/2015/09/">2015年09月</a></li><li><a href="http://10176523.cn/2015/08/">2015年08月</a></li><li><a href="http://10176523.cn/2015/07/">2015年07月</a></li><li><a href="http://10176523.cn/2015/06/">2015年06月</a></li>        </ul>
</section>
    
    <section class="widget">
<h3 class="widget-title">标签</h3>
<ul class="widget-list">
<li><a rel="tag" href="http://10176523.cn/tag/mac/">mac [20]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/java/">java [18]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/%E7%BD%91%E7%BB%9C%E6%8A%80%E5%B7%A7/">网络技巧 [15]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/javascript/">javascript [9]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/%E5%8E%9F%E5%88%9B/">原创 [9]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/html/">html [4]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/%E7%A0%B4%E8%A7%A3/">破解 [4]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/spring/">spring [3]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/druid/">druid [3]</a></li>
<li><a rel="tag" href="http://10176523.cn/tag/MySQL/">MySQL [2]</a></li>
</ul>
</section>
    




    




    
</div><!-- end #sidebar -->
</div><!-- end .row -->
    </div>
</div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值