Java - StackOverflow Error on recursive 2D boolean array method that shouldn't happen.

Posted by David W. on Stack Overflow See other posts from Stack Overflow or by David W.
Published on 2011-01-14T22:23:12Z Indexed on 2011/01/14 22:53 UTC
Read the original article Hit count: 154

Filed under:
|
|
|
|

Hey everyone, I'm working on a runnable java applet that has a fill feature much like the fill method in drawing programs such as Microsoft Paint.

This is how my filling method works:

1.) The applet gets the color that the user clicked on using .getRGB

2.) The applet creates a 2D boolean array of all the pixels in the window, with the value "true" if that pixel is the same color as the color clicked on or "false" if not. The point of this step is to keep the .getRGB method out of the recursive method to hopefully prevent this error.

3.) The applet recursively searches the 2D array of booleans where the user clicked, recording each adjacent point that is "true" in an ArrayList. The method then changes each point it records to false and continues.

4.) The applet paints every point stored in the ArrayList to a user selected color.

All of the above steps work PERFECTLY if the user clicks within a small area, where only a few thousand pixels or so have their color changed. If the user selects a large area however (such as about 360,000 / the size of the applet window), the applet gets to the recursive stage and then outputs this error:

Exception in thread "AWT-EventQueue-1" java.lang.StackOverflowError at java.util.ArrayList.add(ArrayList.java:351) at paint.recursiveSearch(paint.java:185) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190) at paint.recursiveSearch(paint.java:190)
(continues for a few pages)

Here is my recursive code:

public void recursiveSearch(boolean [][] list, Point p){
    if(isValid(p)){
        if(list[(int)p.y][(int)p.x]){
            fillPoints.add(p);
            list[(int)p.y][(int)p.x] = false;

            recursiveSearch(list, new Point(p.x-1,p.y));//Checks to the left
            recursiveSearch(list, new Point(p.x,p.y-1));//Checks above
            recursiveSearch(list, new Point(p.x+1,p.y));//Checks to the right
            recursiveSearch(list, new Point(p.x,p.y+1));//Checks below
            }
        }
    }

Is there any way I can work around an error like this? I know that the loop will never go on forever, it just could take a lot of time.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays