我进行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(外部范围)将其更改为像素值?附:加载的位图呈深红色。
退房如何工作的位图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