获取DIY链接列表类以引发异常

时间:2018-12-06 22:56:47

标签: java exception linked-list

因此,我从头开始制作了LinkedList类。我的append(Object o)方法将一个对象添加到列表的末尾,prepend(Object o)将一个对象添加到列表的开始,indexOf(Object o)返回给定对象的索引。

我唯一无法工作的是我的get(int i)方法。 好吧,那是错误的。它正常工作。就像我想要的那样,它返回列表中给定索引处的对象。唯一的问题是它不会捕获IndexOutOfBounds异常。

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 个答案:

答案 0 :(得分:2)

您的循环会提前返回,因为您执行了以下检查:

if(current.next == null) {
    return null;
}