【问题标题】:linked list throws an IndexOutOfBoundsException链表抛出 IndexOutOfBoundsException
【发布时间】:2013-05-20 17:45:25
【问题描述】:

我有一段涉及 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);
    }

}

【问题讨论】:

  • 您的 indexText 超出范围,但您没有在此处设置。该主题或主题为空,请检查以确保在构建时添加正确的元素
  • indexText() 中的内容;
  • indexText() 是返回一个整数的方法
  • 我已经添加了 indexText();
  • 您能补充一下 Topic.delete() 方法的作用吗?

标签: java indexing linked-list indexoutofboundsexception


【解决方案1】:

那么你需要做边界检查,如果索引是有效的,在删除之前,比如:

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

这将允许您避免 IndexOutOfBoundsException

【讨论】:

    【解决方案2】:

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

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

    如果您检查适合您的 List.size() 的值的语句,我会推荐使用 @nitegazer2003,如果没有调用超过 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
    

    Simular Question about Index 0 and OutOfBoundsException 最后发布的回复解释了类似的答案。不过,您不必阅读他的所有代码。

    Oracle's List 列表及其功能文档的良好来源。

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

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2018-07-31
      • 2016-06-05
      相关资源
      最近更新 更多