當前位置:
首頁 > 最新 > 自動裝箱和拆箱

自動裝箱和拆箱

1

自動裝箱拆箱

基本數據類型:int byte short long float double char boolean

包裝器類型:Integer Byte Short Long Float Double Character Boolean

基本數據類型轉換為包裝器類型,自動裝箱;

Integer的源碼分析:

valueof函數

public static Integer valueof(int i){

if(i>=IntegerCache.low&&i

returnIntegerCache.cache[i+(-IntegerCache.low)]

returnnew Integer(i);

//裝箱的過程會創建對應的對象,這個會消耗內存,所以裝箱的過程會增加內存的消耗,影響性能,盡量避免裝箱;

}

IntegerCache 私有靜態內部類

IntegerCache定義了一個Cache[]數組用來存儲Integer對象,靜態塊裡面完成了對數組的初始化,存入了-128到127之間的Integer對象,否則就創建對象;

Integer類為final修飾時時繼承Number實現Comparable介面

int: intvalue()

包裝器類型轉換為基本數據類型,自動拆箱;

Integer i1=17;

Integer i2=17;

Integer i3=137;

Integer i4=137;

int i5=17;

int i6=137;

i1==i2 true;

i3==i4 false;

i3 equals(i4) true;

i1==i5 true;

i3==i6 true;//Integer自動拆箱為int類型

2

演算法

//如何判斷一個鏈表是否有環,如果有,則返回第一個進入環的接點

public Node getLoopNode(Node head){

if(head==nullhead.next==nullhead.next.next==null) {

return null;

}

Node n1=head.next;//n1---slow

Node n2=head.next.next;//n2----fast

while(n1!=n2) {

if(n2.next==nulln2.next.next==null) {

return null;

}

n2=n2.next.next;

n1=n1.next;

}

n2=head;

while(n1!=n2){

n1=n1.next;

n2=n2.next;

}

return n1;

}

有倆條指針,1個慢指針slow,1個快指針fast,slow每次移動一步,fast每次移動倆步,要使其相遇,來判斷其是否有環,當相遇時l+s+c=2(l+s),l代表進環的之前的長度,s代表環相遇時的位置,c代表環的長度,

所l+s=c , l=c-s ,所以快環則可以從頭結點開始,再一次相遇則為l的距離。


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員食堂 的精彩文章:

TAG:程序員食堂 |