問:java中經常使用數據類型的拆箱與裝箱有什麼坑

 答: 拆箱與裝箱發生通常發生在經常使用的數據類型中,也就是八個基本類型,外加一個Stringjava

    

 數據類型 包裝類 說明
short Short
int Integer
long Long
float Float
double Double
byte Byte
boolean Boolean
char
Character
String String

舉例:緩存

   Integer a = 3 ;// 自動裝箱,java編譯器會這樣處理 Integer a = Integer.valueOf(3) ,jvm

   int b = a; // 自動拆箱,java編譯器會這樣處理 int b = a.intValue();spa

其它類型與上面相似。code

要避免的坑。ci

1. 當有代碼 編譯器

    


String a = "abc";
String b = a;
String c = a + "";
String d = new String("abc");
System.out.println(a == b); // true
System.out.println(b == c); // false
System.out.println(a == c); // false
System.out.println(a.equals(b)); // true
System.out.println(b.equals(c)); // true
System.out.println(a.equals(c)); // true
System.out.println(a == d); // false
System.out.println("abc" == d); // false
編譯

System.out.println("abc" == a); // truetable


Integer h = 100;
Integer i = 100;
Integer j = 200;
Integer k = 200;數據類型

int l = 200;
int m = 200;
System.out.println(h == i); // true
System.out.println(j == k); // false
System.out.println(j == m); // true
System.out.println(l == m); // true


Boolean o = true;
Boolean p = new Boolean(true);
Boolean q = true;
System.out.println(o == p); // false
System.out.println(o == q); // true


  解釋 ,因爲使用自動裝箱,所在jvm會緩存一些數據如int (-128-127)因此h ==i是true, j==k 是false;

    那麼

    I,爲何j==m 爲true呢?

         由於其進行了一次拆箱的操做。轉爲原始類型進行判斷。

    

告訴咱們:

    在程序裏用常量的時候好比一些狀態,儘可能使用127如下的數,使用int定義。

    public final static int OP_OPEN = 1;//打開爲1

相關文章
相關標籤/搜索