查看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> }
<br><br>
Das obige ist der detaillierte Inhalt vonIn Integer ist 1000==1000 falsch und 100==100 wahr. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!