我有一个链表
private LinkedList<Node> vertices;
这是 Node 类
public class Node
{
String value;
linkedList edges ;
public Node()
{
value=null;
edges=new linkedList();
}
}
现在我上面提到的 LinkedList 包含了我图中的节点。我想要做的是将一个字符串值传递给一个方法。这个方法应该检查 LinkedList 中的节点是否包含一个其值等于我传递的值。如果是这样,它应该返回节点的索引。
这是我尝试做的
public Node getNode(String value)
{
int index=vertices.indexOf(value);//this is where the problem is.
//index is getting assigned a value -1
return vertices.get(index);
}
并以这种方式调用该方法
temp2=getNode(header[dest]);
但是对方法vertices.indexOf(value)
的调用返回-1(-1表明它没有它。尽管它有一个值等于值i的节点通过)。我如何检查与我传递的值匹配的节点。
顶点是节点类型,我传递一个字符串值。
最佳答案
在您的节点中,您需要实现 equals 方法,因为 LinkedList 的 indexOf 方法在内部使用 equals 方法来将您传递的 Node 与 List 中的其他现有节点进行比较,如下所示:
public boolean equals(Node otherNode) {
//... compare node values
}
您需要的方法为:
public Node getNode(Node value)//or create node internally with string that you get as input parameter
^^^^^
关于java - java获取LinkedList中包含给定值的节点的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768889/