0

I'm sure this is a newbie question but I have an initialization function in a class that adds two values to an ArrayList. After the first value is added, it outputs the name of it. When the second is added, it should be outputting the first name followed by the second, but it outputs the second twice. I've already looked through things like this happening elsewhere but they all have to do with static variables or variables outside a loop, so any help is appreciated.

public class CommandManager {

    public ArrayList<Command> commands = new ArrayList<Command>();

    public void init() {
        commands.add(new FlightModes()); //Both FlightModes and Keybinds extend Command
        for(Command cm : commands) {
            System.out.println(cm.Alias); //Alias is a public string in Command
        }
        //Outputs "Flightmodes"
        commands.add(new Keybinds());
        for(Command cm : commands) {
            System.out.println(cm.Alias);
        }
        //Outputs "Keybinds" twice
    }
}
  • You will need to add the code for `Command`, `getCommands()`, `keyabinds()` – Pritam Banerjee May 24 '20 at 22:17
  • I updated it - ``getCommands()`` just returned ``commands``, and the same thing happens when I directly change it to ``commands`` so I just updated the code to that. Keybinds and FlightModes extend Command, and Command is just a class that stores ``Alias`` as a public string – Waddles Pines May 24 '20 at 22:23
  • Try `System.out.println(cm);` in both `for`'s and check the output. I'd expect 2 different object instances to be printed on the second `for` and my guess is that the problem is somewhere in `FlightModes`, `Keybinds` or `Command` classes. – MartinBG May 24 '20 at 22:25
  • 1
    You're right. It printed out two different object instances and it turns out the issue is in ``Command``, where Alias is stored as static. I made a mistake in my post, because I assumed it wasn't static. – Waddles Pines May 24 '20 at 22:32

1 Answers1

-1

MartinBG helped me figure it out in a comment. Alias was stored as static in Command, so by setting it for each instance I was just setting the static variable which was the same for both.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 2
    This is why it's important to always provide a [mcve] when making (false) claims like _I've already looked through things like this happening elsewhere but they all have to do with static variables_ – Savior May 24 '20 at 22:39