[英]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.