views:

59

answers:

2

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.

+2  A: 

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);
}
Jaymz
That shouldn't work based on my problem. Perhaps I'm not explaining it right. The pos object isn't ever set to a value, it's set as a reference to the object mTiles[0][i].mPos.
Yeah, my mistake, I just edited my answer as I realised what was going on... still not 100% sure if it'll work though :$
Jaymz
OK, I see you edited. Yes, correct, I need to assign values not a reference...so how do I accomplish that without having to code every .bottom, .top, .left, and .right? Trying your solution now.
+1 think you got it right
willcodejavaforfood
Yes, it works. Thanks. I'm simply frustrated with having to each property of the Rect (aka Rect.top/Rect.bottom). Why can't I copy the value of the whole Rect.
+1  A: 

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

?

OhHiThere
Ahh nice. Never thought of doing it that way. Tested and works. Thanks.