2016-09-18 170 views
0

我想使用ArrayList来表示优先级队列。所以我想在ArrayList的特定位置添加项目。但是,当我运行它,系统告诉我Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 0.线程“main”java.lang.IndexOutOfBoundsException中的异常:索引:10,大小:0 JAVA

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(); 
}} 
+0

你做了什么调试? https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

+0

如果这个应该是一个Queue,那么'enqueue'就没有任何意义,因为'enqueue'在最后添加'Queue'不在任意索引处。既然你叫你优先级队列,我假设你的'enqueue'方法的第二个参数是元素的优先级,而不是它的索引。你应该阅读一些队列。 –

回答

0

因为JavadocArrayListadd(int index, E element)说:

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

抛出:IndexOutOfBoundsException - 如果索引超出范围 (索引< 0 ||指数>尺寸())

你正在做的:它调用

test.enqueu("x",10); 

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

您试图向索引10添加一个字符串,其中ArrayList的大小为0.这意味着s,你正在试试这个,其中index> size()。所以你得到IndexOutOfBoundsException

此外,更多地考虑你的设计和你应该做的。 Enqueue不以这种方式工作,你正在尝试做什么。

相关问题