java byte 判断相等_深入理解Java装箱与拆箱
寫給小白看的Java基礎知識,閱讀本文大概需要7分鐘
Java中有8種基礎數據類型,boolean,char,byte,short,int,long,float,double。從jdk5開始提供了自動裝箱拆箱機制,對應的包裝類型即Boolean,Character,Byte,Short,Integer,Long,Float,Double。
首先解釋一下為什么要引入裝箱和拆箱機制,因為Java是面向對象的語言啊,這樣使用了包裝類后,就可以調用object的一些方法了。都是個人見解,歡迎指正。
Integer裝箱就是將基礎數據類型轉換為對應的包裝器類型;
拆箱就是將包裝器類型轉換為對應的基礎數據類型;
那裝箱和拆箱是如何實現的呢,其實我們在Integer源碼中可以查看,裝箱使用了valueOf()方法,拆箱使用了intValue()。
public static Integer valueOf(int i) {//low=-128if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}public int intValue() {return value;} private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[]; ?static {// high value may be configured by propertyint h = 127;String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}}high = h; ?cache = new Integer[(high - low) + 1];int j = low;for(int k = 0; k < cache.length; k++)cache[k] = new Integer(j++); ?// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127;} ?private IntegerCache() {}}從上述方法的具體實現可以知道,vauleOf已經在cache中創建了[-128,127]范圍的對象數組,當新建的Integer數值在該范圍中,會從對象數組里返回相應的對象。如果超出范圍會重新創建一個對象。
經過上面的解釋我們可以很好地理解上圖的結果,i1和i2都在[-128,127]中,所以返回的是同一個對象,結果為true。而i3和i4超出該范圍,所以兩次都要新建對象,于是結果返回false。
而對于其他幾種包裝類型,也都是利用對應的vauleOf和(Boolean/Character/Byte/Short/Long/Float/Double)Value方法實現裝箱,拆箱。其中Integer、Short、Byte、Character、Long這幾個類的valueOf方法的實現是類似的,Double、Float的valueOf方法的實現是類似的,大家可以在源碼中查看。
Integer a = 1;Integer b = 2;Integer c = 3;Integer d = 3;Integer e = 200;Integer f = 200;Long g = 3L;Long h = 2L; ?System.out.println(c==d);//trueSystem.out.println(e==f);//falseSystem.out.println(c==(a+b));//trueSystem.out.println(c.equals(a+b));//trueSystem.out.println(g==(a+b));//true 當==兩邊有算式時,就比較數值(自動拆箱)System.out.println(g.equals(a+b));//falseSystem.out.println(g.equals(a+h));//true在解釋結果前先來說說==和euqals的區別:
== : 它的作用是判斷兩個對象的地址是不是相等。即,判斷兩個對象是不是同一個對象(基本數據類型比較的是值,引用數據類型比較的是內存地址)。
equals() : 它的作用也是判斷兩個對象是否相等。但它一般有兩種使用情況:
情況 1:類沒有覆蓋 equals() 方法。則通過 equals() 比較該類的兩個對象時,等價于通過“==”比較這兩個對象。
情況 2:類覆蓋了 equals() 方法。一般,我們都覆蓋 equals() 方法來比較兩個對象的內容是否相等;若它們的內容相等,則返回 true (即,認為這兩個對象相等)。
這里解釋一下后三個的結果,==兩邊如果有算式的話,那就只比較內容而不是地址,結果為true。倒數第二個中,a+b和g的類型不同,自然地址也不相同,結果為false。最后一個a+h結果會發生隱式轉換,所以結果為true。
----------------------------------------------------------------------------------------------
歡迎關注我的公眾號預備碼農
總結
以上是生活随笔為你收集整理的java byte 判断相等_深入理解Java装箱与拆箱的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 狙击精英4图文攻略 狙击精英4全关卡剧情
- 下一篇: Monster Audio 使用教程(三