开发者

Changing a variable affects an indirect variable (value vs reference)

开发者 https://www.devze.com 2023-01-17 11:53 出处:网络
Given the following code: Rect pos = new Rect(); for (int i = 0; i < mCols; i++) { pos = mTiles[1][i].getmPos();

Given the following code:

    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);
    }

What I want to do is get the value from

mTiles[1][i].mPos

modify it, and set it in

mTiles[0][i].mPos

The problem is this statement

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

is copying the reference to the object and not the value of the object. Meaning, when I modify pos.top or pos.bottom, the original object gets modified.

I'm guessing I am missing a concept of pass object by reference vs value here...which I thought I understood. What is the fix here? Is it a problem with how I defined my custom class?

Thanks.


You'll need a temporary Rect to change the values with, and only assign the values, not the entire object:

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);
}


How about

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);
}

?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号