[英](Java - Spigot) I have a problem with my PlayerInteractEvent
[英]I have a problem with my Java remove method
作为一项任务,我必须编写自己的 Java remove 方法,该方法使用 node.js 从列表中删除指定索引的元素。 这段代码是从我有 C# class 的时候拿来的,它没有索引参数,所以我不得不在这里实现它。
所以这段代码实际上删除了指定的元素,但它也删除了顶部元素,这是主要问题。
例子:
1| ========Inital list=======
2| 0: S763 ring item 1964 1999 258.61
3| 1: P365 textbook book 1936 2001 64.96
4| 2: G965 forest photo 1929 2014 30.34
5| 3: K637 diary journal 1929 1998 98.68
6| 4: L161 girl photo 1903 1995 54.73
7| ======== End of the list =======
8| ========Testing remove at index 3=======
9| 0: G965 forest photo 1929 2014 30.34
10| 1: L161 girl photo 1903 1995 54.73
11| ======== End of the list =======
如您所见,它确实删除了索引 3 处的元素,但它也删除了索引 0 和 1 处的元素。
这是删除代码:
public E remove(int ind)
{
current = first.findNode(ind);
if (first == null) return current.element;
if (first == current)
{
first = current.next;
size--;
return current.element;
}
while (first.next != null)
{
if (first.next == current)
{
first.next = first.next.next;
return current.element;
}
first = first.next;
}
size--;
return current.element;
}
我想问题出在 while 循环中,但我不知道如何更改它了。 非常感谢您的帮助。
在代码的最顶部,您有:
current = first.findNode(ind);
if (first == null) return current.element;
在第二行中,如果 first 确实是 null,那么程序将在第一行中出现 null 引用异常而崩溃! 如何针对 null 引用调用findNode()
?
此外,如果 first 是 null,current 指向什么? 不也是null吗? 我假设 first 指向列表中的第一个节点,如果 first 是 null 那么您的列表必须是空的?...
我相信您的程序不会非常优雅地处理空列表。
first
要进行更改。创建一个指向 first 的临时局部变量,然后更改它,以便您的 first 仍指向第一个元素:
Node temp = first; // <-- I don't know the TYPE of your node class here
while (temp.next != null)
{
if (temp.next == current)
{
temp.next = current.next;
break;
}
temp = temp.next;
}
size--;
return current.element;
请注意,我不是从循环中间返回,而是调用break;
退出循环。 在下面,我们将正确地减少列表的大小并返回值。 我也从temp.next.next
更改为current.next
。 同样的事情,但它对我来说更“有意义”。
此外,没有对ind
值进行错误检查。 如果它是负数,或者对于列表来说太大了怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.