私は使いたい 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();
}}
回答:
回答№1は0なぜなら Javadoc ために add(int index, E element)
の ArrayList
言う:
このリストの指定された位置に指定された要素を挿入します。 現在その位置にある要素があればそれをシフトし、 右側の後続の要素(インデックスに1を追加します)。
例外:IndexOutOfBoundsException - インデックスが範囲外の場合 (index <0 || index> size())
あなたがやっている:
test.enqueu("x",10);
それは:
Queue.add(10,"x"); // "Queue" is the arrayList
ArrayListのサイズが0のインデックス10に文字列を追加しようとしています。つまり、次のようにしています。 index> size()。だからあなたはなってきています IndexOutOfBoundsException
.
また、あなたのデザインとあなたがすべきことについてもっと考えてください。 Enqueue
あなたがやろうとしていることをこの方法ではうまくいきません。