如何将具有小于x值的hashmap的键放入arraylist中,以便每次键小于x时使其重新生成x值

时间:2015-03-28 05:31:56

标签: java arraylist hashmap bukkit

我正在制作一个Bukkit插件,其中玩家拥有法力和法术。每个法术都有自己的法术力费用,玩家的法力值为20点。

我有ArrayList我存储的法力值少于20的玩家,以及存储玩家当前法力值的HashMap。我需要知道如何制造一种方法,即每秒为玩家增加1点法力值,且法力值不到20点。

每次玩家进入ArrayList时我都需要这样做,然后一旦达到20法力值就将其从列表中删除。

这是我目前的代码:

public HashMap<String, Integer> mana = new HashMap<String, Integer>();
public ArrayList<String> changedMana = new ArrayList<String>();

public void onManaChange(){
  //code goes here
}

2 个答案:

答案 0 :(得分:0)

您可以每秒运行一个任务计时器(这应该放在您的onEnable()方法中):

Bukkit.getServer().getScheduler().runTaskTimer(plugin, new Runnable(){
    public void run(){

    }
},20L,20L); //run this task every 20 ticks (20 ticks = 1 second)

并为ArrayList中的玩家添加法术力:

List<String> toRemove = new ArrayList<String>();

for(String player : changedMana){ //loop through all of the players in the ArrayList
   int current = mana.get(player); //get the player's current mana
   if(current < 20){ //if the player's mana is less than 20
       current++; //add to the player's mana
       mana.put(player, current); //update the player's mana
   }
   else if(current == 20){ //if the player's mana is greater than or equal to 20
       toRemove.add(player); //add the player to the toRemove list, in order to remove the player from the ArrayList later safely
   }
   else{
     //do something if the current mana is > 20, if you don't want to, just remove this
   }
}

changedMana.removeAll(toRemove); //remove players from the changed mana array

因此,如果您的代码位于Main类(extends JavaPlugin)中,您的代码会是什么样子:

public HashMap<String, Integer> mana = new HashMap<String, Integer>();
public ArrayList<String> changedMana = new ArrayList<String>();

@Override
public void onEnable(){
  Bukkit.getServer().getScheduler().runTaskTimer(plugin, new Runnable(){
    public void run(){
      List<String> toRemove = new ArrayList<String>();

      for(String player : changedMana){ //loop through all of the players in the ArrayList
        int current = mana.get(player); //get the player's current mana
        if(current < 20){ //if the player's mana is less than 20
           current++; //add to the player's mana
           mana.put(player, current); //update the player's mana
        }
        else if(current == 20){ //if the player's mana is greater than or equal to 20
           toRemove.add(player); //add the player to the toRemove list, in order to remove the player from the ArrayList later safely
        }
        else{
           //do something if the current mana is > 20, if you don't want to, just remove this
        }
      }

      changedMana.removeAll(toRemove); //remove players from the changed mana array
    }
  },20L,20L);
}

答案 1 :(得分:-1)

将其更改为TreeMap并使用headMap() method