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

hey I have problem with geting array from ArrayList queue = new ArrayList<>();. Do you have any suggestions where I have made mistake?

Manthan Patel
  • 993
  • 1
  • 9
  • 20
  • 2
    Your should probably change `queue.size()` to `queue.size()-1` if you want to access/remove the last element. – Eran Nov 18 '19 at 11:18
  • As I remember `ArrayList` cannot be of priitive type, try use `Integer[]` (instead of int[]) – AsfK Nov 18 '19 at 11:18
  • 1
    @AsfK an `int[]` is not a primitive, it inherits from `Object`, so it's a legitimate base type for a generic collection. – RealSkeptic Nov 18 '19 at 11:22
  • 1
    When you say "I have a problem", please also add what the problem is. Do you get an error message? If so, include it in your question. Do you get behavior that you didn't expect? Then please [edit] the question and add the behavior you expected and what happened instead. – RealSkeptic Nov 18 '19 at 11:23
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – xenteros Nov 18 '19 at 12:49

2 Answers2

1

Your question is not so clear, but I think the problem is in the following line.

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

This won't work since, in Java, indexes are always started with "0". So the index of the last element will be queue.size()-1. So the above code will return index out of bound exception.

Correct your code as follows;

int[] get = queue.get(queue.size()-1);
Chathura Buddhika
  • 2,067
  • 1
  • 21
  • 35
1

From List::get(int index)

Returns the element at the specified position in this list.
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

In your question when you are writing below line:

queue.get(queue.size());

then it violate the index >= size() condition because you are passing queue.size()

Pass the index value b/w 0 and queue.size() - 1 to get the element.

Example:

int[] get = queue.get(queue.size()-1);
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89