Java是按值传递还是按引用传递?

Java是按值传递还是按引用传递?,java,function,parameter-passing,Java,Function,Parameter Passing,我执行了3次测试,以检查位图是否通过值或引用传递,但在运行以下代码后感到困惑: public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); V v = new V(this); setContentView(v); } class V extends

我执行了3次测试,以检查位图是否通过值或引用传递,但在运行以下代码后感到困惑:

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仍然是一件事

  • b2仍然是hv thing00

  • b2(1,1)是255


问题是测试2和测试3相互矛盾。测试2显示b2是通过值传递的,因为b2没有变为null。但是如果位图是按值传递的,那么在test3中,setPixel()应该处理b2(函数范围内的那个)的副本,但是为什么b2(外部范围)会更改它的像素值呢?p、 加载的位图是深红色。

这与Java的工作方式有关,而不是与Android或位图的工作方式有关。Java通过值传递引用。更详细的解释可以在

中找到,JAVA总是按值传递

每次将变量传递给java函数时,您都在复制其引用,当您从java
return
中的函数获得结果时,它是对象引用的新副本

下面是您的
test()
函数的工作原理:

  • 当您通过b2抛出调用测试(b2);您将获得对b2对象的新引用,称为b
  • 然后将该引用设置为null。您不会影响范围外的引用,因为您无论如何都无法访问它
希望有帮助。请看一下这个详细的问题:


查看位图的工作原理此描述有点误导。听起来像是说你得到了整个位图的副本,而你真正得到的是位图对象引用的副本。我想我得到了。调用settpixel()时,新的ref.仍链接到我的外部作用域b2,因此.setpixel将影响外部作用域b2。但在调用test()时,我只是将参数b2链接到null的地址,因此对参数b2的任何更改都不会影响外部作用域b2,因为参数不再链接到外部b2。我说得对吗?