Why do object assignments refer to memory locations when primitive types don't? [duplicate]

蓝咒 提交于 2019-12-02 10:07:42
T.J. Crowder

The exact same thing is done whether the variables are of primitive type or reference type: The value held in the variable is copied to the other variable.

The only difference is that the value held in a variable with a reference type is a reference to the actual thing (the object), not the actual thing itself, whereas the value in the variable for primitive types is the actual thing (the primitive value).

Say you have:

int a = 5;

That's a bit like Joe having a piece of paper (the variable a) with 5 written on it.

Now:

int b = a;

The value in a is copied into b. That's a bit like Mary coming along, getting out a piece of paper, and copying down what's on Joe's piece of paper (the number 5).

Now, say you have:

Map a = new HashMap();

It's a bit like Joe having a piece of paper with his address written on it. The piece of paper is the variable a; the HashMap object is his house.

Now:

Map b = a;

The value in a is copied into b. It's like Mary coming along and getting out a piece of paper and copying Joe's address from his piece of paper onto it. The house hasn't been copied, just the information about where it is.

That's what an object reference is: Information (like a number) telling the JVM where the object is in memory.

I go into it in some detail in this answer (Java), and this one (which is about JavaScript, but the concept of values, variables, and object references is the same in the two languages [and many others]).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!