2016-09-18 172 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不以這種方式工作,你正在嘗試做什麼。

相關問題