所以我从头开始做了一个linkedlist类。我的append(object o)方法将对象添加到列表的末尾,prepend(object o)将对象添加到列表的开头,indexof(object o)返回给定对象的索引。
我唯一做不到的就是我的get(inti)方法。嗯,那是假的。它工作正常。它返回列表中给定索引处的对象,就像我希望的那样。唯一的问题是它不会捕获indexoutobounds异常。
public class LinkedList {
//node class
public class Node {
public Object data;
public Node next;
public Node (Object data) {
this.data = data;
}
}
//variables
protected Node head;
//after this is my append, prepend, etc methods but they aren't important
public Object get(int index) {
if (index < 0)
return null;
Node current = null;
try {
if (head != null) {
current = head.next;
for (int i = 1; i < index; i++) {
if (current.next == null) {
return null;
}
current = current.next;
}
if (current.data == null) {
throw new IndexOutOfBoundsException();
}
else
return current.data;
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("Warning: Index out of bounds");
}
return current;
}
如果索引i中没有元素,我不希望此代码返回null,而是要捕获异常。但是,无论我做什么,它都不会捕获异常。请帮我找出问题所在并加以解决。谢谢您!
1条答案
按热度按时间g9icjywg1#
因为执行了以下检查,所以循环会提前返回: