Recursion in Java enums?

Posted by davidrobles on Stack Overflow See other posts from Stack Overflow or by davidrobles
Published on 2010-03-17T23:53:28Z Indexed on 2010/03/18 0:31 UTC
Read the original article Hit count: 691

Filed under:
|
|

I've been trying for 3 hours and I just can't understand what is happening here.

I have an enum 'Maze'. For some reason, when the method 'search' is called on this enum it's EXTREMELY slow (3 minutes to run). However, if I copy the same method to another class as a static method, and I call it from the enum 'Maze' it runs in one second!

I don't understand why? is there any problem with recursive methods in Java enums?? What am I doing wrong?

public enum Maze
{
    A("A.txt"), B("B.txt");

    // variables here...

    Maze(String fileName)
    {
        loadMap(fileName);
        nodeDistances = new int[nodes.size()][nodes.size()];
        setNeighbors();
        setDistances();
    }

    ... more methods here ...

    private void setDistances()
    {
        nodeDistances = new int[nodes.size()][nodes.size()];

        for (int i = 0; i < nodes.size(); i++) {
            setMax(nodeDistances[i]);
            // This works!!!
            TestMaze.search(nodes, nodeDistances[i], i, 0);
            // This DOESN'T WORK
            //search(nodes, nodeDistances[i], i, 0);
        }
    }

    public void setMax(int[] a) {
        for (int i=0; i<a.length; i++) {
            a[i] = Integer.MAX_VALUE;
        }
    }

    public void search(List<Node> allNodes, int[] distances, int curNodeIndex, int curDist)
    {
        if (curDist < distances[curNodeIndex])
        {
            distances[curNodeIndex] = curDist;

            for (Node n : allNodes.get(curNodeIndex).getNeighbors()) {
                search(allNodes, distances, n.getNodeIndex(), curDist + 1);
            }
        }
    }
}

public class TestMaze
{
    public static void search(List<Node> allNodes, int[] distances, int curNodeIndex, int curDist)
    {
        if (curDist < distances[curNodeIndex])
        {
            distances[curNodeIndex] = curDist;

            for (Node n : allNodes.get(curNodeIndex).getNeighbors()) {
                search(allNodes, distances, n.getNodeIndex(), curDist + 1);
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about enums