线程"main"中的异常java.lang.IndexOutOfBoundsException:索引:10,大小:0.JAVA [英] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 0. JAVA

查看:85
本文介绍了线程"main"中的异常java.lang.IndexOutOfBoundsException:索引:10,大小:0.JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use an ArrayList to represent the priority queue. So I want to add item on specific position of the ArrayList. But when I run it, system told me 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();
 }}

推荐答案

因为

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

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

抛出:IndexOutOfBoundsException-如果索引超出范围(索引< 0 ||索引> size())

Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

您正在做

test.enqueu("x",10);

哪个调用:

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

您正在尝试将一个字符串添加到索引10,其中ArrayList的大小为0.这意味着,您正在尝试执行此操作,其中 index> size().因此,您将得到 IndexOutOfBoundsException .

You are trying to add an string to index 10, where the size of ArrayList is 0. That means, you are trying this, where index > size(). So you are getting IndexOutOfBoundsException.

此外,请更多地考虑您的设计以及应该做什么.入队无法按照您尝试的方式工作.

Also, think more about your design and what you should do. Enqueue does not work this way what you are trying to do.

这篇关于线程"main"中的异常java.lang.IndexOutOfBoundsException:索引:10,大小:0.JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆