0

我有一段涉及 LinkedList 的代码。以下是

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

是来自名为 Topic 的 LinkedList 的方法。这些都在 GUI 设计中实现。方法

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

工作正常,但是

topic.delete(index) 

扔给我一个

IndexOutOfBoundsException

我简要解释了这些方法:read(name) 和 send(text) 接受 String 参数并读取主题及其消息列表,并以接收方式向主题发送消息。delete(index) 应该从主题中删除索引指定的消息。但是,错误消息告诉我 Size 为 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();
    }
}

将这些添加到此问题中:

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);
    }

}
4

2 回答 2

1

如果索引有效,则需要在删除之前进行边界检查,例如:

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

这将允许您避免 IndexOutOfBoundsException

于 2013-05-25T05:44:44.803 回答
0

你好迪尔沙特阿卜杜瓦利!

当您收到回复说您的索引大小为 0 表示对象未添加到列表中或尚未添加时,这就是为什么您要删除索引值为 2 的所述对象的原因,例如它会抛出一个 IndexOutOfBoundsException,因为索引的大小仅为 0。确保您正在向您的列表添加值,否则它将不会被填充。

我建议您使用@nitegazer2003 if 语句检查适合您的 List.size() 的值,您没有调用超过 List 大小的整数,这会给您 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's List List 及其特性文档的良好来源。

我希望这对您有所帮助或指出正确的方向!祝你好运!

于 2013-05-25T06:13:48.807 回答