为什么这没有意义?删除节点

时间:2013-03-28 11:47:56

标签: java linked-list nodes

我有代码,用于输入和增加计数器以进行打印和删除。我添加了一些打印行来查看链表和当前位置之间的计数差异,这就是我得到的:

Enter a command from the list above (q to quit): 
2
Deleted: e                e                5                $5.0
 Current record is now first record.
4
5
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
        at java.util.LinkedList.entry(LinkedList.java:365)
        at java.util.LinkedList.get(LinkedList.java:315)
        at bankdata.command(bankdata.java:158)
        at bankdata.main(bankdata.java:314)
Java Result: 1
BUILD SUCCESSFUL (total time: 18 seconds)

输入命令2,删除当前节点命令。当前节点是链表中的最后一个节点,其大小为5,技术上意味着0-4。

那么我在运行此代码时会怎样:

//currentAccount is a static int that was created at the start of my code.
//It got it's size because the int is saved every time a new node is made.
//The most recent size correlates with the last position in the linked list.
            int altefucseyegiv = accountRecords.size();
            System.out.println("Deleted: " + accountRecords.get(currentAccount)
                    + "\n Current record is now first record.");
            System.out.println(currentAccount);
            System.out.println(accountRecords.size());
            accountRecords.remove(currentAccount);
            System.out.println("Deleted: " + accountRecords.get(currentAccount)
                    + "\n Current record is now first record.");
            if(altefucseyegiv == 1)
            {
                currentAccount = -1;
            }
            else
            {
                currentAccount = 0;
            }
            records.currentAcc(currentAccount, accountRecords);
            return;

我收到此错误???

我很困惑!因为我正在移除.get(4),这意味着我只是删除了第5个元素而我并不是说爱情。有人可以解释并可能帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:4)

抛出IOFB异常
System.out.println("Deleted: " + accountRecords.get(currentAccount)
                + "\n Current record is now first record.");

你已经删除了第5个元素,所以现在没有要显示的第5个元素(记住数组位置从0开始)

答案 1 :(得分:3)

尝试

Object obj = accountRecords.remove(currentAccount);
System.out.println("Deleted: " + obj + "\n Current record is now first record.");

我假设您已初始化currentAccountaccountRecords.size() - 1accountRecords有5个节点。

然后currentAccount的值为4,您要从列表中删除第4个元素,只留下accountRecords只有4个元素。

然后,您尝试从accountRecords.get(4)只有4个元素且有效元素索引为accountRecords的列表中提取0..3,这就是您收到错误的原因。

答案 2 :(得分:1)

我认为你的错误是你的println:

System.out.println("Deleted: " + accountRecords.get(currentAccount)
                + "\n Current record is now first record.");

< - 你得到了IndexOutOfBoundsException,因为你删除了列表的最后一个条目,或者我错了? 也许试试:
    System.out.println(“已删除:”+ accountRecords.get(currentAccount-1)                     +“\ n当前记录现在是第一个记录。”);