Increase the value of Integers in a HashMap?

Discussion in 'Plugin Development' started by DirtyStarfish, Oct 3, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    DirtyStarfish

    Hey!

    I'm trying to create a HashMap with players as the key, and an Integer as the value.
    Code:
    public static Map<Player, Integer> test = new HashMap<Player, Integer>();
    I want to increase the value of all of the Integers every minute.
    I have written the code for the scheduler, but I don't know what to do from here.

    So, basically, how can I increase the value of all the Integers contained in the HashMap by 10 for example.

    Any help is appreciated!
     
  2. Well, basically you have to iterate over all keys and increase their values.

    Code:java
    1. Iterator<Integer> iter = test.values().iterator();
    2. while (iter.hasNext()) {
    3. ++iter.next();
    4. }
     
  3. Offline

    ZerothAngel

    @Pandemoneus That won't work. You have to stuff the integers back into the map

    @DirtyStarfish
    Code:
    for (Map.Entry<Player, Integer> me : test.entrySet()) {
        int count = me.getValue();
        count += 10;
        me.setValue(count);
    }
    
    If you're doing this in another thread, you should probably synchronize all access to the map. (Or maybe use a ConcurrentMap instead.)
     
    DirtyStarfish likes this.
  4. It does work, the iterator changes elements in a HashSet which is backed up by the map.
     
  5. Offline

    ZerothAngel

    I just tried out your method (because I hate contradicting people), and it doesn't even compile.

    ++ is only valid on variables.
     
  6. Offline

    wwsean08

    just checking, is this for just online people, if it is, you could use a for each loop on the online player array, incrementing them.
     
  7. Offline

    DirtyStarfish

    No, I'm trying to make a magic plugin for my server and need a way for people to regenerate some of their power every 30 seconds or so. :)

    This didn't work for me either, but thanks for trying to help :)

    ZerothAngel got it right, it works great! Thank you!
     
  8. Offline

    wwsean08

    dang, too bad since that would be so much easier lol. You might be able to go through the worlds folder (say world/players), which should contain a .dat for every player who has ever joined the server. Then use that to find them in the hash map, and do what you want as far as increasing them. You will just have to remember to drop the .dat off the end of the file name.
     
Thread Status:
Not open for further replies.

Share This Page