在工作中使用==埋下的坑這篇博文中,我們看到當使用基本類型的時候==是完全沒有問題的,部分或者混合使用基本類型和裝箱基本類型的時候,就可能出現問題了,那么我們可能會想基本類型和裝箱基本類型有什么區別和聯系哪?下面以int和Integer為例講講我的看法。int和Integer非常的像,所有的基本類型和其對應的裝箱基本類型都非常的像,但是他們之間也是有區別的,他們之間的區別是什么哪?
為了明白他們之間的區別和聯系,我們一起看看下面這段簡單的代碼和羅織在代碼之間的結論吧!
1:TestIntMain.java——包含基本類型和裝箱基本類型的區別和聯系的結論注釋
import java.util.ArrayList; import java.util.List; public class TestIntMain { public static void main(String [] args){ /** * 區別1: * int 聲明的變量不能直接賦值為null * Integer 聲明的變量能直接賦值為null */ // int _int_ = null;//不能直接賦null Integer _Integer_ = null;//可以直接賦null /** * 區別2: * int 聲明的變量,存儲就是一個數值,不能調用方法,它也沒有方法可調用 * Integer 聲明的變量,是一個對象,它有對應的變量、方法,它可以自由的調用 */ int _int = 99; Integer _Integer1 = new Integer(99); //一個整數值,不能調用方法 // System.out.println("_int type is : "+_int.getClass().getSimpleName()+"_int value is : "+_int.toString()); System.out.println("_int value is : "+_int); //一個對象,可以調用它的方法,屬性等等 System.out.println("_Integer1 type is : "+_Integer1.getClass().getName()+" _Integer1 value is : "+_Integer1); /** * 自動裝箱和拆箱 * 自動裝箱:我的理解是將基本類型的變量,自動轉換為裝箱基本類型的對象的過程 * 自動拆箱:我的理解是將裝箱基本類型的對象,自動轉換為基本類型的變量的過程 * 1:這是在Java1.5發行版本中增加的功能 * 2:目的是為了模糊基本類型和裝箱基本類型之間的區別,減少使用裝箱基本類型的繁瑣性 * 3:這樣做也有一定的風險,比如:對於裝箱基本類型運用==操作符幾乎總是錯誤的,裝箱的操作會導致高的開銷和不必要的對象創建 */ int _int1 = new Integer(99);//對應的匿名對象變成了一個整數值,自動拆箱 int _int2 = _Integer1;//_Integer1對象變成了一個整數值,自動拆箱 // System.out.println("_int1 type is : "+_int1.getClass().getSimpleName()+"_int1 value is : "+_int1.toString()); System.out.println("_int1 value is : "+_int1); Integer _Integer = 99;//對應的整數值,直接給你對象也沒問題,自動裝箱 System.out.println("_Integer type is : "+_Integer.getClass().getName()+" _Integer value is : "+_Integer); // List<int> list_ = new ArrayList<int>(); List<Integer> list = new ArrayList<Integer>(); list.add(_int);//_int 此時相當於是一個Integer類型的對象了,自動裝箱 list.add(_Integer); } }
2:TestIntMain.class——包含基本類型和裝箱基本類型的自動裝箱和拆箱的實現方式
import java.util.ArrayList; public class TestIntMain { public TestIntMain() { } public static void main(String[] args) { Object _Integer_ = null;//Integer _Integer_ = null; 編譯后是這樣的哦 byte _int = 99;//int _int = 99; 編譯后是這樣的哦 Integer _Integer1 = new Integer(99); System.out.println("_int value is : " + _int); System.out.println("_Integer1 type is : " + _Integer1.getClass().getName() + " _Integer1 value is : " + _Integer1); int _int1 = (new Integer(99)).intValue();//自動拆箱的實現方式 int _int2 = _Integer1.intValue();//自動拆箱的實現方式 System.out.println("_int1 value is : " + _int1); Integer _Integer = Integer.valueOf(99);//自動裝箱的實現方式 System.out.println("_Integer type is : " + _Integer.getClass().getName() + " _Integer value is : " + _Integer); ArrayList list = new ArrayList(); list.add(Integer.valueOf(_int));//自動裝箱的實現方式 list.add(_Integer); } }
3:參考
http://mindprod.com/jgloss/intvsinteger.html
http://www.careerride.com/Java-QA-integer-vs-int.aspx
https://www.quora.com/What-is-the-difference-between-an-integer-and-int-in-Java