我正在编写一个函数来反转链表,最后我的数据结构如下所示:
OriginalPointer - > [Obj 1]< - [Obj 2]< - [Obj 3]< - [Obj 4]< - ReversedList
OriginalPointer是我传递给函数的东西,而ReverseList是我正在返回的指针。在java中,一旦我返回了我的ReverseList指针,RawPointer是否被垃圾收集清理干净,或者该指针总是在那里?好奇。
答案 0 :(得分:0)
java上的所有对象都存储在堆中,并且这些对象链接在一起。因此,当您反转链接列表时,您所做的只是更改对象的引用,一个对象指向。所以假设,堆有4个对象obj1,obj2,obj3,obj4。所有对象都包含nextNode属性,该属性告诉它们下一个节点。反转列表后,您所做的就是更改该对象的nextNode属性值。因此,默认情况下,您之前的链接将被删除,我认为GC不需要任何内容。
答案 1 :(得分:0)
GC仅在程序中的任何位置没有对象的引用时收集对象。只要您在另一个节点或临时节点中保存对其中一个节点的引用,就不会收集它。原始指针'你传入我假设是列表引用变量,它仍然指向列表的开头(现在结束),除非你改变它。像这样的局部变量只有在它们所处的方法完成并从中返回时才会被销毁。
答案 2 :(得分:0)
Here's your example, in Java syntax:
a1 b1 b2 c1 c2
a1 0 4 0 5 0
b1 4 0 0 0 0
b2 0 0 0 0 6
c1 5 0 0 0 0
c2 0 0 6 0 0
You start with four objects in the heap (the four nodes of your list), and one variable on the stack, Node yourList = /* [Obj 1] <- [Obj 2] <- [Obj 3] <- [Obj 4] */;
yourList = reverse(yourList);
. This variable holds a reference to yourList
's location in the heap. When Obj 1
is called it is handed the reference to reverse()
and iterates through each object, reversing the list. Finally it returns a reference to Obj 1
. The Obj 4
variable is then updated to reference yourList
. Since Obj 4
in turn references the other objects, none of them will be garbage collected.
All that happens to Obj 4
is its value is updated. It previously stored the location (address) of yourList
, now it stores the location of Obj 1
. The previous value isn't garbage collected, it's overwritten. So after Obj 4
returns we end up with the same four objects on the heap, and the same one variable on the stack.
答案 3 :(得分:0)
Java is always pass by value, which means that when you will call Color.parseColor("#000000")
, you will send a value of your pointer as a parameter.
Any change you make to your objList will have impact to your original list, unless you clone your list.
GC removes any object from the ram once it is not reachable within your code.
By the end of doReverce(List<obj> objList)
, it will remove any reference created there. In this case, it will remove the secondary reference inside the method, but since you have a reference from your main, your list object will still be in the ram. Once you have no references in your object, GC will collect (remove) it. The code I am refering is below. Keep in mind that you don't need to return a pointer of your object, since you already have it.
doReverse