开发者

Java - remove last known item from HASHMAP on MAP!s

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

private Map<S开发者_C百科tring, Player> players = new HashMap<String, Player>();

How do I remove last known item from that? Maybe somethign like this?

hey = Player.get(players.size() - 1);
Player.remove(hey);


The problem is, a HashMap is not sorted like a list. The internal order depends on the hashCode() value of the key (e.g. String). You can use a LinkedHashMap which preserves the insert order. To remove the last entry on this you can use an iterator in combination with a counter which compares to the size and remove the last entry.

It's so easy. Try this:

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


I'm a little bit confused. First of all, you're saying that you've got a new ArrayList and you're illustrating this with a line that creates a new HashMap. Secondly, does the Player class really have static methods like get(int) and remove(Object)?

HashMap doesn't have a particular order, ArrayList (as any other List) does.

Removing from an ArrayList

If you've got a list of players, then you can do the following:

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

Here, I've used the remove(int) method of List, which allows to remove an item at an arbitrary index.

Removing from a HashMap

If you've got a map of players, there's no such thing as "the last item". Sure, you can iterate over the map and one of the items will pop out last, but that doesn't mean anything. Therefore, first you have to find out what you want to remove. Then you can do the following:

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);

Here, I've used the remove(Object) method of Map. Note that in order to remove some key-value pair, you have to show the key, not the value.


There's no "first" and "last" in a HashMap. It's unordered. Everything is accessible by its key, not by index.


You cannot delete from HashMap like that. You need to use LinkedHashMap.


Simple, just do something of this effect.

1) Get a keyset iterator;
2) Create a Key somelastKey = null
3) Iterate through the iterator and assigning somelastKey until iterator finishes.
4) finally, do players.remove(somelastKey);

Bear in mind that HashMap is unordered, it depends on Object's hashCode to determine insertion order.

Instead of using HashMap, try using LinkedHashMap which keeps a predictable iteration order.

Hope this helps....


You'll probably have to extend HashMap, override put so that it caches the key, and then create a new method that just removes the key that was cached.

Unfortunately, this will only let you remove the most recently added. If you need to remove the most recently added multiple times (without inserting in-between the removes), you're out of luck.

In that case, I'd probably do the same overrides, just write the keys to a List. So you'd have both a list and a Map.


When adding:

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

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

Other than that there's really no way without using a LinkedHashMap or in some way creating your own wrapper map or extending HashMap.


You shouldn't be using a raw hashmap anywhere because things like this happen.

Get in the habit of wrapping your collections in business logic classes.

See, in your case right now you need to associate these two related variables--your hashmap and a "Last entered" item so you can remove it.

If you need to remove the last item from some other class, you need to pass both items.

Any time you find yourself passing 2 or more items together into more than one API, you are probably missing a class.

Create a new class that contains the hashmap and a "lastAdded" variable. Have put and remove methods that are just forwarded to the hashmap, but the put method would also set the lastAdded variable.

Also be sure to add a removeLast() method.

NEVER allow access to your hashmap outside this class, it needs to be completely private (this is what I mean by wrapped). In this way you can ensure it doesn't get out of sync with the lastAdded variable (also completely private).

Just to reiterate getters and setters for these variables would be a terrible idea (as they are with nearly all actual OO code).

You will quickly find a bunch of other methods that NEED to be in this class in order to access data inside your hashmap--methods that never felt right in their current location. You will probably also notice that those methods always have an additional parameter or two passed in--those parameters should probably be members of your new class.

Once you get in the habit of doing actual OO design (via refactoring in this case), you'll find your code MUCH more manageable. To illustrate this point, if you find later that you need multiple levels of "delete last", it will be TRIVIAL to add to your class because it will be extremely clear exactly what methods can modify your hashtable and where your new "stack" of lastItems should be located--in fact it's probably a 2 line code change.

If you do not make this wrapper class, various locations will each have code to set "lastAdded" when they add code to the hashtable. Each of those locations will have to be modified, some may be in other classes requiring you to pass your new stack around with the hashtable. It will be easier to get them out of synch if you forget to change one location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜