Search code examples
javaiterationequivalent

Iterating over a set of hardcoded strings


I have the below blob of code. However, this looks ugly, and it gets tedious if I want to, for some bizarre reason, add another limb:

player.get("legs").setPosition(   playerInfo.get("legs").getPos().x,   playerInfo.get("legs").getPos().y   );
player.get("thighs").setPosition( playerInfo.get("thighs").getPos().x, playerInfo.get("thighs").getPos().y );
player.get("torso").setPosition(  playerInfo.get("torso").getPos().x,  playerInfo.get("torso").getPos().y  );
player.get("arms1").setPosition(  playerInfo.get("arms1").getPos().x,  playerInfo.get("arms1").getPos().y  );
player.get("arms2").setPosition(  playerInfo.get("arms2").getPos().x,  playerInfo.get("arms2").getPos().y  );
player.get("head").setPosition(   playerInfo.get("head").getPos().x,   playerInfo.get("head").getPos().y   );

As you can see, this is gettig very repetitive, so what is a better way of writing this? If i was as fluent in java as I am in perl I would go by something like this pseudo-code:

foreach my $limb ( qw( legs thighs torso arms1 arms2 head )) {
    player.get($limb).setPosition(   playerInfo.get($limb).getPos().x,   playerInfo.get($limb).getPos().y   );
}

Basically, instead of repeating each line on which i will have to substitute the string three times, i would like to iterate over each string and insert it into one single line of code.


Solution

  • You can also use a enum instead.

    [1] if you change your player to use enum instead of string (my favorite)

    enum limbs {legs,thighs,torso,arms1,arms2,head};
    
    public static void main(String[] args) throws Exception {
        for (limbs limb : limbs.values()){
            player.get(limb).setPosition(
                playerInfo.get(limb).getPos().x,   playerInfo.get(limb).getPos().y   );
        }
    }
    

    [2] if you want to keep using strings to index

    enum limbs {legs,thighs,torso,arms1,arms2,head};
    
    public static void main(String[] args) throws Exception {
    
        for (limbs limb : limbs.values()){
            player.get(limb.toString()).setPosition(
                playerInfo.get(limb.toString()).getPos().x,   playerInfo.get(limb.toString()).getPos().y   );
        }
    }