我有一些代碼可以接受用戶輸入並增加一個計數器以用於打印和刪除目的。我加了一些打印線看計有什麼不同鏈表和當前位置之間,這是我得到了什麼:爲什麼這不合理?刪除節點
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)th,這意味着我只是刪除第五個元素,我不是說愛。有人可以解釋,並可能幫助我解決這個問題嗎?
是的,您可以在打印索引時訪問此元素。但是你打電話:'accountRecords.remove(currentAccount);'。嘗試輸出當前索引和大小後,可能會有助於理解問題。 –
我用一個catch來檢查這個異常,我仍然有相同的大小:/ –
最重要的是,如果我將currentAccount大小減1,那麼它不會刪除最後一個節點,而是最後一個節點之前的那個節點不會刪除最後一個節點。 –