开发者

Android - Share Objects by Reference

hey people, I have created a class which extends application to share certain variables. Within each activity I then use an object of that class (globalstate) as so:

gs = (GlobalState) getApplication();

I then declare local variable which reference the shared ones such as:

boolean localStr = gs.str;

Now I am under the impression this would be passed a a reference and therefore any change to localStr would be reflected in str within globalstate. However this does not seem to be the case.

Some variables created in this manor such as an array of object seem to be passed as re开发者_高级运维ference and therefore any changes are reflected within globalstate however for almost every other variables (booleans, strings & ints) it seems the changes aren't reflected and therefore are being copied rather than referenced.

Have I done something wrong or is this how android works, if so how can i pass by reference? Thanks.


boolean is a value type, Java doesn't use a reference to store it. It's the same for all Java primitive types (int, long, ...). Strings are different, they are reference types but are immutable as explained by Johan Sjöberg.

That's why when using an ArrayList (for example) you will get an error if you try to use a value type like new ArrayList<boolean>(). But new ArrayList<Boolean>() will work because Boolean is a reference type, not a value type.

To avoid your problem you should use your reference everywhere (use gs.str instead of creating a local variable, localStr). I can explain it better if you don't really understand what I'm saying.


That's not only how android works, that's how java works. Strings are immutable, meaning they cannot be changed. Every time you try and modify a string a new string is created; hence the following code will leave the string named first unchanged:

String first = "first";    // First points to mem address e.g., 0x1
String second = first;     // Second also does
second = "something else"; // Second now points to 0x2, first still to 0x1

It's exactly the same behaviour for all primitive types (int, boolean etc).

However, when you pass a List of objects, alterations of the list contents will be changed everywhere. This is since your objects share the same list reference (which itself doesn't change, only it's contents).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜