日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

自动装箱与自动拆箱的一些问题

發布時間:2025/4/16 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自动装箱与自动拆箱的一些问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

今天打算復習一下Java基礎,之前學的太快速了,現在暑假,好好把那些細節看一下

復習到自動裝箱和自動拆箱的時候,這里有個很有趣的現象

  • Integer?n1?=?100;? ?
  • Integer?n2?=?100;?? ?
  • System.out.println(n1?==?n2);???? ?
  • ?
  • Integer?n3?=?200;?? ?
  • Integer?n4?=?200;?? ?
  • System.out.println(n3?==?n4);? ?
  • 你們猜猜結果是什么? 第一個是true,第二個是false。有趣吧。

    其實它們是相當于

  • Integer?n1?=?Integer.valueOf(100);???? ?
  • Integer?n2?=?Integer.valueOf(100);??? ?
  • System.out.println(n1?==?n2);?? ?
  • ?
  • Integer?n1?=?Integer.valueOf(200);???? ?
  • Integer?n2?=?Integer.valueOf(200);??? ?
  • System.out.println(n1?==?n2);??? ?
  • ? ?
  • 所以那個valueOf()就是問題的關鍵啦,看一下這個函數的源碼

  • /**?? ?
  • ??*?Returns?an?{@code?Integer}?instance?representing?the?specified?? ?
  • ??*?{@code?int}?value.??If?a?new?{@code?Integer}?instance?is?not?? ?
  • ??*?required,?this?method?should?generally?be?used?in?preference?to?? ?
  • ??*?the?constructor?{@link?#Integer(int)},?as?this?method?is?likely?? ?
  • ??*?to?yield?significantly?better?space?and?time?performance?by?? ?
  • ??*?caching?frequently?requested?values.?? ?
  • ??*?? ?
  • ??*?This?method?will?always?cache?values?in?the?range?-128?to?127,?? ?
  • ??*?inclusive,?and?may?cache?other?values?outside?of?this?range.?? ?
  • ??*?? ?
  • ??*?@param??i?an?{@code?int}?value.?? ?
  • ??*?@return?an?{@code?Integer}?instance?representing?{@code?i}.?? ?
  • ??*?@since??1.5?? ?
  • ??*/?? ?
  • ?public?static?Integer?valueOf(int?i)?{??? ?
  • ?????assert?IntegerCache.high?>=?127;??? ?
  • ??if?(i?>=?IntegerCache.lo&&i<=IntegerCache.high)???????? ?
  • ?return?IntegerCache.cache[i?+?(-IntegerCache.low)];??? ?
  • ?????return?new?Integer(i);??? ?
  • ?}?? ?
  • 所以我們知道了,對于-128到127之間的數,Integer.valueOf(99)返回的是緩存中的對象,所以兩次調用valueOf返回的是同一個對象,故結果是true.而Integer.valueOf(199)返回的則是重新實例化的對象,故結果是false.

    ?

    自動拆箱

    ?

  • Integer?n1?=?10; ?
  • int?t1?=?n1; ?
  • Integer?n2?=?10; ?
  • int?t2?=?n2; ?
  • System.out.println(t1?==?t2);?
  • ?

  • Integer?n1?=?199; ?
  • int?t1?=?n1; ?
  • Integer?n2?=?199; ?
  • int?t2?=?n2; ?
  • System.out.println(t1?==?t2);?
  • 兩次的結果是true。

    ?

    所以我們要注意自動裝箱時候數值的范圍的選擇~~

    轉載于:https://blog.51cto.com/lovelydd/934278

    總結

    以上是生活随笔為你收集整理的自动装箱与自动拆箱的一些问题的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。