我正在尝试执行 get(int index) 方法,该方法返回列表中指定索引处的元素,但我看不到要返回的内容。 tempNode之后我最终会得到什么?
public E get(int index) throws IndexOutOfBoundsException {
Node tempNode = head;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("index was out of bounds");
}
for (int i = 0; i < index; i++) {
tempNode = tempNode.getmNextNode();
}
return tempNode.;
}
我正在使用 Node 类:
public class Node<E> {
private E mElement;
private Node<E> mNextNode;
Node(E data) {
this.setmElement(data);
}
public E getmElement() {
return this.mElement;
}
public void setmElement(E element) {
this.mElement = element;
}
public Node<E> getmNextNode() {
return this.mNextNode;
}
public void setmNextNode(Node<E> node) {
this.mNextNode = node;
}
}
最佳答案
你有一个 getmElement()
方法Node
这将返回您想要的数据。
但是,目前您的get(int)
方法是使用原始 Node
变量,因此无法要求它提供适当的返回类型。目前tempNode.getmElement()
只会返回 Object
.
您需要做的是使用Node<E>
像这样:
public E get(int index) throws IndexOutOfBoundsException {
Node<E> tempNode = head;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("index was out of bounds");
}
for (int i = 0; i < index; i++) {
tempNode = tempNode.getmNextNode();
}
return tempNode.getmElement();
}
关于java - java中的get(int index)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60288770/