Search code examples
javaalgorithmcollections

Is there any way you can interate through a list of method calls in Java?


Say if I wanted to put those methods calls under the runnable (ahead(), turnLeft(), back() etc), into a collection list or array and one executes after other. Can this be done? This is robot game calledn "RobotCode", by the way. Thanks in advance.

import java.awt.*;
import java.util.ArrayList;

public class NeuBot extends Robot
{

    int rapidFire = 2;
    //RobotHit rbHit = new RobotHit(null);
    public String name;
    boolean firing = false;
    int trigger;
    int turnDirection = 2;
    final int MOVES = 5;
    boolean wasHit = true;
    int moveOne = 1;
    int moveTwo = 2;
    int moveThree = 3;

    ArrayList<Integer> moveLst = new ArrayList<Integer>();

    public void run()
    {

        while (true)
        {
            //Methods Defined within the Robot Class 
            ahead(100);
            back(200);
            turnLeft(180);
            turnRight(180);
            onScannedRobot(null);
            onHitRobot(null);
        }

    }

    //Robot Has Target
    public void onScannedRobot(ScannedRobotEvent e)
    {

        for (int i = 0; i < MOVES; ++i)
        {
            firing = true;
            fire(rapidFire);
            if (firing == true)
            {
                back(50);
                out.println("Moved Back"); //TestX
            }
        }
        turnRight(10);
        ahead(20);

    }

    //
    public void onHitRobot(HitRobotEvent e)
    {
        out.println("Hit");
        wasHit = true;
        if (wasHit == true)
        {
            //Move Ahead And Fire
            ahead(20);
            fire(rapidFire);
            out.print("Fired Again!");
        }

    }
}

Solution

  • Straightforward solution: use a list of Runnable like in:

    List<Runnable> commands = List.of(
        () -> ahead(100),
        () -> back(200),
        () -> turnLeft(180),
        () -> turnRight(180),
        () -> onScannedRobot(null),
        () -> onHitRobot(null)
    );
    

    above creates an unmodifiable list, but usual lists can also be used like in and commands added dynamically:

    List<Runnable> commands = new ArrayList<>():
    commands.add( () -> ahead(100) );
    commands.add( () -> back(200) );
    // ...
    

    These lists can be used in Java 8 Streams:

    commands.forEach(Runnable::run);
    

    or in usual loops:

    for (Runnable command : commands) {
        command.run();
        // additional statements, e.g. Thread.sleep(...) for some delay
    }
    

    A more complex solution would be to create your own Command interface (or use Runnable) and implementing classes which would store the needed arguments.