简体   繁体   English

如何在更改原始引用变量后再次引用Java对象

[英]How to reference a Java object again after changing the original reference variable

I thought that this would be a good exercise for understanding a bit more about objects. 我认为这对理解更多关于物体的做法是一个很好的练习。

I'm trying to figure out how to reference an object again after changing the object's original reference variable. 我试图找出在更改对象的原始引用变量后如何再次引用对象。

Take the following code: 请使用以下代码:

String person = "person a"; //Line 1
person = "person b";        //Line 2

Now, line 1 creates a new String object with the reference variable being person . 现在,第1行创建一个新的String对象,引用变量为person Line 2 assigns that reference variable to another new String object. 第2行将该引用变量分配给另一个新的String对象。 The original String object now has no reference variable. 原始String对象现在没有引用变量。

How would I circle back and reference the original String object that is already in memory on line 1? 我将如何圈回并引用第1行内存中已有的原始String对象? Say, assigning the reference variable person back to the original String object? 比方说,将引用变量person分配回原始的String对象? As a subsequent thought (not that I know that much about garbage collection), but is the original object eligible for garbage collection being that it does not have a reference variable anymore after line 2, and is therefore ineligible to be referenced again? 作为后来的想法(并不是我对垃圾收集知之甚少),但是原始对象是否有资格进行垃圾收集,因为它在第2行之后不再有引用变量,因此没有资格再次引用?

I am seeing the hashCode() method, and also the System.identityHashCode() but can't figure out how to implement it all in order to reference the original object again. 我看到hashCode()方法,以及System.identityHashCode()但无法弄清楚如何实现它以便再次引用原始对象。

Line 3: person = "person a"; 第3行: person = "person a"; Java has a String intern cache. Java有一个String实习生缓存。 Now if it wasn't a String (or some other cached type), the answer would be you don't. 现在,如果它不是String (或其他一些缓存类型),答案就是你没有。 Because the referecned object was eligible for garbage collection (it has no references anymore). 因为引用的对象有资格进行垃圾回收(它不再有引用)。 You can validate this like, 你可以验证这个,像,

String person = "person a"; //Line 1
System.out.println(person.hashCode());
person = "person b";        //Line 2
person = "person a";        //Line 3
System.out.println(person.hashCode());

which will display the same hashCode twice; 这将两次显示相同的hashCode; because it's the same instance. 因为它是同一个实例。

After you assign the new String 分配新String后

person = "person b";

The first one vanishes.. You won't be able to use it because you have lost his address. 第一个消失了......你将无法使用它,因为你丢失了他的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM