Java教程——int與Integer的區別,javaintinteger

來源:互聯網
上載者:User

Java教程——int與Integer的區別,javaintinteger

首先說一下int和Integer的區別:

下面看具體例子:

 1 package syswar.cc; 2  3 public class IntegerCompare { 4  5     public static void main(String[] args) { 6         // TODO Auto-generated method stub 7         Integer a1 = 2; 8         Integer a2 = 2; 9 10         Integer b1 = 150;11         Integer b2 = 150;12 13         Integer c1 = new Integer(2);14         Integer c2 = new Integer(2);15 16         Integer d1 = new Integer(150);17         Integer d2 = new Integer(150);18 19         System.out.println("a1==a2?" + (a1==a2));20         System.out.println("b1==b2?" + (b1==b2));21         System.out.println("c1==c2?" + (c1==c2));22         System.out.println("d1==d2?" + (d1==d2));23     }24 25 }                

 

運行結果:

a1==a2?trueb1==b2?falsec1==c2?falsed1==d2?false

 

為什麼是這個結果呢?我們先比較a和b兩組,Integer初始化時,緩衝Integer對象資料,這些Integer對象對應的int值為byte範圍,即[-128,127]。

當直接給Integer賦int值時,如果值得範圍為[-128,127],Integer直接從緩衝中取Integer對象,因此,當直接賦的int值處於[-128,127]時,Integer對象為相同的對象。

而通過new方式取的Integer對象,是直接從堆裡面分配的對象,因此,不管具體的int值為多少,==判斷的結果都是false

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.