更改变量会影响间接变量(值与参考值)

时间:2010-09-26 20:32:01

标签: java android eclipse

给出以下代码:

    Rect pos = new Rect();
    for (int i = 0; i < mCols; i++) {
        pos = mTiles[1][i].getmPos();
        pos.top = pos.top - size;
        pos.bottom = pos.bottom - size;
        mTiles[0][i].setmPos(pos);
    }

我想要做的是从

获取价值
mTiles[1][i].mPos

修改它,并在

中设置它
mTiles[0][i].mPos

问题在于这句话

pos = mTiles[1][i].getmPos();

正在复制对象的引用,而不是对象的值。这意味着,当我修改pos.top或pos.bottom时,原始对象会被修改。

我猜我错过了通过引用vs值传递对象的概念......我以为我理解了。这是什么修复?我是如何定义自定义类的?

感谢。

2 个答案:

答案 0 :(得分:2)

您需要一个临时的Rect来更改值,并且只分配值,而不是整个对象:

Rect pos;
for (int i = 0; i < mCols; i++) {
    pos = new Rect();
    pos.top = mTiles[1][i].getmPos().top - size;
    pos.bottom = mTiles[1][i].getmPos().bottom - size;
    mTiles[0][i].setmPos(pos);
}

答案 1 :(得分:1)

怎么样

Rect pos = new Rect();
for (int i = 0; i < mCols; i++) {
    pos = new Rect(mTiles[1][i].getmPos());
    pos.top = pos.top - size;
    pos.bottom = pos.bottom - size;
    mTiles[0][i].setmPos(pos);
}