2015-10-04 24 views
0

這裏是我的代碼:在聲明動態數組的收縮功能在堆棧

private void shrink(){ 
int length = top+1; 
    if(length<=MINCAPACITY || top<<2 >= length) 
     return; 
     length = length + (top<<1); 
     if(top < MINCAPACITY) length = MINCAPACITY; 
     int[] newstack = new int[length]; 
     System.arraycopy(stackRep, 0 , newstack, 0 , top+1); 
     stackRep = newstack; 
    } 

在我的書,據說此操作陣列縮小到一半,如果超過3/4空。任何人都可以請向我解釋這是怎麼發生在這個代碼?我懷疑這個操作是在第一個if語句和長度語句中發生的?

+0

那麼*確切*部分代碼你不明白? –

+0

3,4,5,6行 –

回答

0

Java數組不能改變長度。這是做什麼的,計算新的長度,創建一個新長度的數組,並從舊數組中複製它的東西,然後使舊數組引用新數組。

int length = ... // this will be the new arrays length 
int[] newstack = new int[length]; // this is the new array 
System.arraycopy(stackRep, 0 , newstack, 0 , top + 1); // stuff is copied to the new array 
stackRep = newstack; // old array is now the new array 

不知道這是否回答您的問題

編輯:

通過了「部分改變長度」我想,你想知道,什麼這些事:<<>>。他們是移位操作員,你可以找到更詳細的描述,例如here

他們基本上做到這一點:

  • x << n - 乘x通過2n
  • x >> n力量 - 通過2xn

功率所以10 << 12010 << 38010 >> 1510 >> 22(這裏失去了精度,因爲這些操作員只是簡單地移位)。

+0

我需要它如何改變那個長度的部分。 –

+0

這是否回答你的問題? –

+0

嗯,仍然沒有。我需要知道這個代碼是如何將數組大小減半的。 –