鉴于此代码:
String first = "Hello world";
String second = first;
first = "Something else";
Run Code Online (Sandbox Code Playgroud)
在执行之后,变量是否second指向变量first在第一个赋值中指向的相同内存实例(相同的"Hello world"),或者它是一个完全不同的内存区域(另一个内存区域也称为"Hello world") ?
我想知道是否在第二行(String other = originalString)中进行多次赋值会导致任何性能损失,或者它是否与分配任何其他对象一样快.
T.J*_*der 10
执行之后,变量second会指向变量在第一个赋值中首先指向的相同内存实例(相同的"Hello world"),还是一个完全不同的内存区域(另一个内存区域也称为"Hello world") ")?
相同的内存区域.
这是你在每个阶段所拥有的:
String first = "Hello world";
Run Code Online (Sandbox Code Playgroud)
给你:
+-------+ +---------------+ | first |---------->| "Hello world" | +-------+ +---------------+
然后
String second = first;
Run Code Online (Sandbox Code Playgroud)
+--------+
| second |----\
+--------+ | +---------------+
+---->| "Hello world" | (same memory as above)
+--------+ | +---------------+
| first |----/
+--------+
然后
first = "Something else";
Run Code Online (Sandbox Code Playgroud)
+--------+ +---------------+ | second |---------->| "Hello world" | (same memory as above) +--------+ +---------------+
+--------+ +------------------+ | first |---------->| "Something else" | +--------+ +------------------+
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |