2013-02-06 83 views
0

我進行3次測試,以檢查是否該位圖是按值或引用傳遞而感到困惑後,我運行下面的代碼:Java按值或通過引用傳遞?

public class MainActivity extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    V v = new V(this); 
    setContentView(v); 
} 

class V extends View{ 
    Bitmap b1; 
    Bitmap b2; 

    public V(Context context) { 
     super(context); 
     //load bitmap1 
     InputStream is = getResources().openRawResource(R.drawable.missu); 
     b1 = BitmapFactory.decodeStream(is); 
     //testing start 
     b2 = b1; 
     //b1 = null; 
     //1.test if b1 and b2 are different instances 
     if(b2 == null){ 
      Log.d("","b2 is null"); 
     } 
     else{ 
      Log.d("","b2 still hv thing"); 
     } 
     //2.test if b2 is pass by ref or value 
     test(b2); 
     if(b2 == null){ 
      Log.d("","b2 is null00"); 
     } 
     else{ 
      Log.d("","b2 still hv thing00"); 
     } 
        //3.want to further confirm test2 
     b2 = b2.copy(Config.ARGB_8888, true); 
        settpixel(b2); 
     if(b2.getPixel(1, 1) == Color.argb(255,255, 255, 255)){ 
      Log.d("","b2(1,1) is 255"); 
     } 
     else{ 
      Log.d("","b2(1,1) is not 255"); 
     } 
    } 

    void test(Bitmap b){ 
     b = null; 
    } 
    void settpixel(Bitmap b){ 
     b.setPixel(1, 1, Color.argb(255,255, 255, 255)); 
    } 
}} 

結果:

  • B2仍然HV事情

  • B2仍然HV thing00

  • B2(1,1)爲255

問題是測試2和3相互矛盾。 test2顯示b2是通過值,因爲b2不成爲空。但是,如果位圖是通過值傳遞的,那麼在test3中,setPixel()應該在b2(函數範圍中的那個)的副本上工作,但爲什麼b2(外部範圍)將其更改爲像素值?附:加載的位圖呈深紅色。

+0

退房如何工作的位圖http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/ 1.5_r4/android/graphics/Bitmap.java#Bitmap.nativeCopy%28int%2Cint%2Cboolean%29 – weakwire

回答

0

JAVA發現總是按值傳遞

每次傳遞一個變量到Java的功能要複製它的參考,當你得到結果的時間java中的函數return它是對象引用的新副本。

現在,這裏是一步步的test()功能是如何工作的:

  • 當您通過B2罰球調用測試(B2);你會得到一個新的對b2對象b的引用。
  • 然後,您將該引用設置爲null。您不會影響範圍內的參考,因爲無論如何您都無法訪問它。

希望有所幫助。請看看這個詳細的問題:

Is Java "pass-by-reference" or "pass-by-value"?

+1

這個描述有點令人誤解。這聽起來像你說你得到了整個Bitmap的副本,當你真正得到的是對Bitmap對象的引用的副本。 –

+0

我想我明白了。當調用settpixel()時,新的ref。仍然連接到我的外部作用域b2,所以.setpixel將影響外部作用域b2。但是在調用test()時,我只是將參數b2鏈接到null地址,所以對參數b2的任何更改都不會影響外部作用域b2,因爲參數不再鏈接到外部b2。我對麼? – VictorLi