【问题标题】:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 0. JAVA线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:10,大小:0。JAVA
【发布时间】:2016-09-18 17:54:39
【问题描述】:

我想使用ArrayList 来表示优先级队列。所以我想在ArrayList 的特定位置添加项目。但是当我运行它时,系统告诉我Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 0.

public class PriorityQueue 
{
public ArrayList<String> Queue=new ArrayList<>();

public void enqueu(String s, int p)
{
    Queue.add(p,s);
}

public void dequeu()
{
    String temp=Queue.get(Queue.size()-1);
    Queue.remove(temp);
}
public void print()
{
    String[] print=new String[Queue.size()];
    print=Queue.toArray(print);
    for(int i=0;i<Queue.size();i++)
    {
        System.out.println(print[i]);
    }


}

 public static void main(String[] args)
 {
     PriorityQueue test= new PriorityQueue();
     test.enqueu("x",10);
     test.enqueu("Y",1);
     test.enqueu("Z",3);

     test.print();
 }}

【问题讨论】:

  • 你的enqueue 如果这应该是一个队列就没有任何意义,因为enqueueQueue 的末尾添加而不是在任意索引处。由于您称您为类 Priority Queue,我假设您的 enqueue 方法的第二个参数将是元素的优先级而不是它的索引。您可能应该阅读有关队列的一些内容。

标签: java arraylist


【解决方案1】:

因为ArrayListadd(int index, E element)Javadoc 说:

在此列表中的指定位置插入指定元素。 移动当前在该位置的元素(如果有)和任何 右侧的后续元素(将其索引加一)。

抛出:IndexOutOfBoundsException - 如果索引超出范围 (index size())

你正在做:

test.enqueu("x",10);

调用:

Queue.add(10,"x"); // "Queue" is the arrayList

您正在尝试将字符串添加到索引 10,其中 ArrayList 的大小为 0。这意味着,您正在尝试此操作,其中 index > size()。所以你得到IndexOutOfBoundsException

此外,请多考虑您的设计以及您应该做什么。 Enqueue 不能按照您尝试的方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2013-07-29
    • 2018-10-29
    • 2017-01-02
    • 2016-12-28
    相关资源
    最近更新 更多