Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java store methods in arrays?

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it'd be a bit neater (and out of curiosity to see if it could be done), but it doesn't compile when I do it this way, because it doesn't recognize an item in an array as a method, I think. This is what I have:

String[] moveArray = {moveRight,moveDown,moveLeft,moveUp};
for (i = 0; i < 4; i++) {
    while (myWumpus.moveArray[i]) {
        myWumpus.moveArray[i];
        generator.updateDisplay();
    }
}

When I try compile I get

not a statement myWumpus.moveArray[i]();
';' expected myWumpus.moveArray[i]();

(It refers to the first statement in the while loop)

So, I think it's maybe because I'm making it an Array of type String? Is there a type Method? Is this at all possible? Any solutions welcome :). Also, I can get it to work using 4 while loops, so you don't need to show me that solution. Thanks!

like image 258
Paul Avatar asked Jan 31 '10 18:01

Paul


Video Answer


2 Answers

You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:

Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
for (i = 0; i < 4; i++) {
    while (myWumpus.moveArray[i]) {
        moveArray[i].move();
        generator.updateDisplay();
    }
}
like image 97
Avi Avatar answered Oct 20 '22 13:10

Avi


Yes, you can store methods in arrays using Reflection, however it is likely that what you actually want to do in this situation is use polymorphism.

As an example of polymorphism in relation to your problem - say you created an interface as follows:

public interface MoveCommand {
    void move();
}

You can then create implementations as follows:

public class MoveLeftCommand implements MoveCommand {
    public void move() {
        System.out.println("LEFT");
    }
}

etc. for the other move options. You could then store these in an MoveCommand[] or collection like a List<MoveCommand>, and then iterate over the array/collection calling move() on each element, for example:

public class Main {

    public static void main(String[] args) {
        List<MoveCommand> commands = new ArrayList<MoveCommand>();
        commands.add(new MoveLeftCommand());
        commands.add(new MoveRightCommand());
        commands.add(new MoveLeftCommand());

        for (MoveCommand command:commands) {
            command.move();
        }
    }

}

Polymorphism is very powerful, and the above is a very simple example of something called the Command Pattern. Enjoy the rest of your Wumpus World implementation :)

like image 35
brabster Avatar answered Oct 20 '22 13:10

brabster