gpt4 book ai didi

java - 链表和抛出异常

转载 作者:行者123 更新时间:2023-12-02 08:56:12 24 4
gpt4 key购买 nike

我的问题是关于实现一个方法 get(int n) ,该方法应该返回索引 n 处的元素(索引从 0 开始)。如果索引越界,则应抛出异常 IllegalArgumentException。这是我写的代码,它是正确的还是我应该更改一些内容?

(int size)数组列表

public Item get(int size) {
Node<Item> n= head;
for (int i=0; i<=size;i++)
n=n.next;

if ( size < 0 ) { throw new UnsupportedOperationException();}
return null;*

最佳答案

您可以在循环之前简化第一个检查:

if (head == null || size < 0) {
throw new UnsupportedOperationException();
}

在循环内,您必须检查您是否落在列表之外:

if (n == null) {
throw new UnsupportedOperationException();
}

最后,在循环之后,您必须返回找到的实际元素:

return n.getItem();

另请注意,sizen 是令人困惑的变量名称,您最好将它们称为 index当前。考虑到我的所有建议,代码应如下所示:

public Item get(int index) {

if (head == null || index < 0) {
throw new UnsupportedOperationException();
}

Node current = head;

for (int i = 0; i < index; i++) {
if (current == null) {
throw new UnsupportedOperationException();
}
current = current.next();
}

return current.getItem();

}

关于java - 链表和抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com