Java - remove the last known item from HASHMAP on a MAP! S

OK, so this BIT is different. I have a new HashMap

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

How to remove the last known item from this? Maybe something like this?

hey = Player.get(players.size() - 1);
Player.remove(hey);
+3
source share
8 answers

I'm a little confused. First of all, you say that you have a new one ArrayList, and you illustrate this with the line that creates the new one HashMap. Secondly, does the class really Playerhave static methods, such as get(int)and remove(Object)?

HashMapdoes not have a specific order ArrayList(like any other List).

Delete from ArrayList

If you have a list of players, you can do the following:

private List<Player> players = new ArrayList<Player>();
// Populate the list of players
players.remove(players.size() - 1);

remove(int) List, .

HashMap

, , " ". , , , . , . :

private Map<String, Player> players = new HashMap<String, Player>();
// Populate the map of players
// Find the key of the player to remove
players.remove(toRemove);

remove(Object) Map. , , .

+4

, HashMap , . hashCode() (, String). LinkedHashMap, . , , .

. :

Map<String, Player> players = new LinkedHashMap<String, Players>();
List<String> list = new ArrayList<String>(players.keySet());
map.remove(list.get(list.size()-1));
+6

HashMap "" "". . , .

+2

, - .

1) ;
2) Key somelastKey = null
3) somelastKey .
4) , do players.remove(somelastKey);

, HashMap , hashCode, .

HashMap LinkedHashMap, .

, ...

+1

HashMap. LinkedHashMap.

+1

, , HashMap, put , , , , .

, . ( ), .

, , , . , , .

0

:

String key; Player value;
lastKey = key;
map.put(key, value);

//...later...
Player lastAdded = map.remove(lastKey);

, LinkedHashMap - - HashMap.

0

-, .

-.

, - " ", .

, .

, , API, , , .

, - lastAdded. , hashmap, put lastAdded.

removeLast().

, ( , ). , , ( ).

( OO-).

, , hashmap, . , , , - , , .

OO ( ), , . , , " ", TRIVIAL , , - "" lastItems - , , 2- .

If you do not create this wrapper class, in different places each will have code to set "lastAdded" when they add code to the hash table. Each of these places needs to be changed, some of them may be in other classes requiring you to pass a new column using a hash table. It will be easier to get them out of sync if you forget to change one location.

0
source

Source: https://habr.com/ru/post/1760386/


All Articles