简体   繁体   中英

java - remove object from map/array collection if it exists

Players are added to an array

Player[] players = new Player[] 

A hashmap is created in another class

private Map <String, Player> players; 

players = new HashMap<String, Player>();

Then players are added to the collection

public void addPlayer(Player player) {
  players.put(player.getPlayerId(), player); 
}

Need to write a method that removes a player if they existed and returen true/false

public boolean removePlayer(Player player)

So far I have:

public boolean removePlayer(Player player) {
  //check player key exists, returns true/false
  if (players.containsKey(player.getPlayerId())){
     players.remove(player.getPlayerId());
     return true;
  }
  else
     return false;
}

Will this work? how can I test it?

It is a good approach to write an unit test (jUnit, testNG) to check the particular methods. It will improve overall quality of your code and you will be sure it works as designed.

Even more if you change the code, the test will tell if something become wrong less than in a second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM