2013-02-06 111 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