如何从ArrayList <>获取数组

时间:2019-11-18 11:15:09

标签: java arrays arraylist

ArrayList<int[]> queue = new ArrayList<>();
       if (isValid(x, y, colorFill, colorBoundary, graphics)){
           int[] add = new int[2];
           add[0]=x;
           add[1]=y;
           queue.add(add);

       }
       while (!queue.isEmpty()){
          int[] get = queue.get(queue.size());
          graphics.putPixel(get[0],get[1],colorFill);
          queue.remove(queue.size());...}

嘿,我从ArrayList queue = new ArrayList <>();获取数组时遇到问题。你有什么 我犯错的建议?

2 个答案:

答案 0 :(得分:1)

您的问题不太清楚,但我认为问题出在下一行。

int[] get = queue.get(queue.size());

这将不起作用,因为在Java中,索引始终以“ 0”开头。因此,最后一个元素的索引将为queue.size()-1。因此,上面的代码将返回index out of bound exception

按如下所示修改您的代码;

int[] get = queue.get(queue.size()-1);

答案 1 :(得分:1)

来自List::get(int index)

  

返回此列表中指定位置的元素。
  抛出
  IndexOutOfBoundsException-如果索引超出范围(索引<0 ||索引> = size())

在下面的行中写问题:

queue.get(queue.size());

然后它违反了index >= size()条件,因为您传递了 queue.size()

传递索引值b / w 0queue.size() - 1以获得元素。

示例:

int[] get = queue.get(queue.size()-1);