首页 >Java >java教程 >Integer中1000==1000为false而100==100为true

Integer中1000==1000为false而100==100为true

PHP中文网
PHP中文网原创
2017-07-13 18:12:401626浏览
查看Integer.java类,会发现有一个内部私有类,IntegerCache.java,它缓存了从-128到127之间的所有的整数对象。<br>如果在这个区间内,他就会把变量当做一个变量,放到内存中;但如果不在这个范围内,就会去new一个Integer对象。<br>所以例子中i1和i2指向了一个对象。因此100==100为true。<br>比较Integer的值,比较靠谱的是通过Integer.intValue()这样出来的就是int值,就可以直接比较了,或者equals()比较。<br><br>
<span style="color: #008080"> 1</span> <span style="color: #008000">/**</span>
<span style="color: #008080"> 2</span> <span style="color: #008000"> * Created by hunt on 2017/6/3.
</span><span style="color: #008080"> 3</span>  <span style="color: #008000">*/</span>
<span style="color: #008080"> 4</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span><span style="color: #000000"> TestInteger {
</span><span style="color: #008080"> 5</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span><span style="color: #000000"> main(String[] args) {
</span><span style="color: #008080"> 6</span>         Integer i1 = 100, i2 = 100<span style="color: #000000">;
</span><span style="color: #008080"> 7</span>         System.out.println(i1 == i2);<span style="color: #008000">//</span><span style="color: #008000">true</span>
<span style="color: #008080"> 8</span>         Integer i3 = 1000, i4 = 1000<span style="color: #000000">;
</span><span style="color: #008080"> 9</span>         System.out.println(i3 == i4);<span style="color: #008000">//</span><span style="color: #008000">false</span>
<span style="color: #008080">10</span> 
<span style="color: #008080">11</span> 
<span style="color: #008080">12</span>         System.out.println(i3.intValue() == i4.intValue());<span style="color: #008000">//</span><span style="color: #008000">true</span>
<span style="color: #008080">13</span>         System.out.println(i3.equals(i4));<span style="color: #008000">//</span><span style="color: #008000">true
</span><span style="color: #008080">14</span> 
<span style="color: #008080">15</span> 
<span style="color: #008080">16</span>         <span style="color: #008000">//</span><span style="color: #008000">Integer  与 int 类型比较(==)比较的是值。</span>
<span style="color: #008080">17</span>         <span style="color: #0000ff">int</span> i5 = 1000<span style="color: #000000">;
</span><span style="color: #008080">18</span>         System.out.println(i3 == i5);<span style="color: #008000">//</span><span style="color: #008000">true</span>
<span style="color: #008080">19</span> 
<span style="color: #008080">20</span> <span style="color: #000000">    }
</span><span style="color: #008080">21</span> }
View Code

 

<br><br>

以上是Integer中1000==1000为false而100==100为true的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn