簡體   English   中英

鏈表拋出IndexOutOfBoundsException

[英]linked list throws an IndexOutOfBoundsException

我有一段涉及LinkedList的代碼。 以下內容

topic.read() 
topic.delete() and 
topic.send() 

是LinkedList中稱為Topic的方法。 這些正在GUI設計中實現。 方法

 topic.read(name) 
 topic.send(text) 

工作正常,但是

topic.delete(index) 

把我扔了

IndexOutOfBoundsException

我簡要地解釋了這些方法:read(name)和send(text)使用String參數,讀取主題及其消息列表,並將消息發送給主題。 delete(index)應該從主題中刪除索引指定的消息。 但是,錯誤消息告訴我大小為0。

相關的部分:(我認為該部分應該足夠,如果需要,可以添加更多的部分)

public void act(String s)
{
    topic = new Topic(s, topics);
    if (s.equals("Read"))
        setEditorText(topic.read(readText()));
    else if (s.equals("Delete"))
        topic.delete(indexText());
    else if (s.equals("Send"))
    {   
        topic.send(getEditorText(), sendText());
        clear();
    }
}

將這些添加到此Quesion:

private JTextField indexText = new JTextField(10);
public int indexText()
{
    return Integer.parseInt(indexText.getText());
}

public class Topic {
    private LinkedList<String> messages = new LinkedList<String>();

    public void delete(int index)
    {   
    messages.remove(index - 1);
    }

}

然后,在刪除之前,您需要進行邊界檢查(如果索引有效),例如:

if (index > 0 && index <= messages.size()) {
    messages.remove(index - 1)
};

這將使您避免IndexOutOfBoundsException

您好Dilshat Abduwalli!

當您收到一個響應,說您的索引大小為0時,意味着沒有將對象添加到列表中或尚未添加,這就是為什么您要刪除例如索引值2的對象的原因一個IndexOutOfBoundsException,因為索引的大小僅為0。確保將值添加到List中,否則將不會填充它。

我建議使用@ nitegazer2003 if語句,如果您檢查將適合List.size()的值,則不會調用超過列表大小的整數,這將使您獲得IndexOutOfBoundsException。

使用for循環仔細檢查您的列表值。

for(int i = 0; i < list.size(); i++)
    System.out.println(list.get(i)); //Print the Strings in the list (Assuming its a list of Strings)

要么

for(int i = 0; i < list.size(); i++)
     System.out.println(list.getSize()); //Test the size of the list

關於索引0和OutOfBoundsException的類似問題上次發布的響應解釋了類似的答案。 您不必閱讀他的所有代碼。

Oracle的List是List及其功能文檔的良好來源。

希望這對您有所幫助或為您指明正確的方向! 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM