所以我有一个名为“SNode
s”的节点阵列(它们是我自己创建的一个类,它们实际上只是一个基本节点,它包含一个字符串和一个指向下一个节点的指针)。如何使用变量创建对我的对象的引用?
我有一个方法叫做insertValue()
,它接受你想要放入一个值的索引和你想要SNode
包含的字符串。但是,如果通过的索引已包含SNode
,我希望新值成为SNode
的“下一个”节点(实质上是在每个索引空间中创建一个链接的节点列表)。
private int insertValue(int arrayPos, String element){//Checks for collisions with another SNode, and inserts the SNode into the apppropriate 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
正处于变量targetNode
创建的,但targetNode
没有链接到实例化后的数组位置。我假设它基本上是将数据从第2行的数组位置复制到变量中,但随后变成了它自己的独立实体。
那么我怎么有targetNode
实际参考和影响SNode
? (当我重复上下贯通的节点在已经占据阵列空间链表这样的方式,targetNode指向正确的)
注:为了简单起见,我已经离开了在SNode
中使用setNext()
方法的行将链接列表中的前一个节点链接到其下一个节点。
啊哈!好吧,所以*初始*时间我需要一个'if'语句来检查数组索引是否为空。如果是这样,我需要直接编辑数组索引来添加新的SNode.但在此之后,我可以使用'targetNode'指向它后面的链表对象,并且它将正常工作。谢谢,这完全解决了我的问题! – Guy