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

痞子三分冷 提交于 2019-12-02 15:39:33

问题


I have a bit of an odd question regarding how primitive types work in Java. When using Objects when you assign an ObjectA to be ObjectB be like such

Rectangle ObjectB = new Rectangle();
ObjectA = ObjectB;

Any calls to ObjectA refer now to ObjectB's memory location. However when using integers or other primitive types this is not the case. For example

int x = 3;
int y = x;
int x = 5;
return y;

y will return 3, the value of x when y was initialized.

The question I have is why does assignment for objects create references in memory, whereas primitives make a copy of the values of each other? Other than the fact that this is useful, how is this implemented in Java?

I'd appreciate anyone who can provide me a greater understanding of how assignment works between primitive types and objects.


回答1:


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]).



来源:https://stackoverflow.com/questions/34952927/why-do-object-assignments-refer-to-memory-locations-when-primitive-types-dont

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