我進行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