【发布时间】:2017-10-31 09:13:34
【问题描述】:
所以我有一个充满节点的数组,称为“SNodes”(它们是我自己创建的一个类。它们实际上只是一个包含单个字符串和指向下一个节点的指针的基本节点)。
我有一个名为insertValue() 的方法,它接收您要在其中放入值的索引和您希望SNode 包含的字符串。但是,如果传递的索引中已经包含 SNode,我希望新值成为 SNode 的“下一个”节点(本质上是在每个索引空间中创建节点的链接列表)。
private int insertValue(int arrayPos, String element){//Checks for collisions with another SNode, and inserts the SNode into the appropriate spot in the array
SNode targetNode = array[arrayPos];//What I want to be a reference to the node at the desired position in the array
while (targetNode != null){//If an SNode already exists in that position, keeps iterating down until it gets to a non-existant SNode.
targetNode = targetNode.getNext();//getNext is a method in my SNode that just returns a reference to that SNode's "nextNode" variable.
}
targetNode = new SNode(element);
return arrayPos;
}//end insertValue
我的问题是,在我运行这个方法之后,它并没有在所需的数组位置创建一个新节点,即使在数组点为空时第一次运行也是如此。
如果我将targetNode = new SNode(element); 更改为array[arrayPos] = new SNode(element);,它显然会将SNode 插入到数组中就好了,这让我相信正在发生的事情是在变量@ 下创建了新的SNode 987654331@,但那个targetNode在实例化后并没有链接到数组位置。我假设它本质上是将第 2 行的数组位置中的数据复制到变量中,然后变成它自己的独立实体。
那么我如何让targetNode 实际引用并影响SNode? (这样,当我向下遍历已经占用的数组空间中的节点链表时,targetNode 指向的是正确的。)
注意:为简单起见,我省略了在SNode 中使用setNext() 方法将链表中的前一个节点链接到其下一个节点的行。 p>
【问题讨论】:
标签: java variables pass-by-reference pass-by-value