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?

5
  • 2
    Your should probably change queue.size() to queue.size()-1 if you want to access/remove the last element. Commented Nov 18, 2019 at 11:18
  • As I remember ArrayList cannot be of priitive type, try use Integer[] (instead of int[]) Commented Nov 18, 2019 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. Commented Nov 18, 2019 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. Commented Nov 18, 2019 at 11:23
  • 1
    Does this answer your question? What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? Commented Nov 18, 2019 at 12:49

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.