tags:

views:

129

answers:

8

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

private Map<String, 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);
+2  A: 

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));
fprobst
It's ok. but how do i remove from hashmap.
Dan
+1  A: 

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.

Bolo
A: 

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....

The Elite Gentleman
"Last" is arbitrary here.
Mark Peters
True, that's why the OP needs to iterate through keys.
The Elite Gentleman
Huh? That still removes a completely arbitrary element, not the last one added.
Mark Peters
...and besides, I think you have to pass the key to Java's Hashmap remove() method, not the value...
froadie
Thanks froadie...updated....
The Elite Gentleman
+1  A: 

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

froadie
It's ok. I want to test something. How do i remove from hashmap
Dan
remove any arbitrary object? call the remove() method with the key that you want to remove. for example: `players.remove("Player1");`
froadie
A: 

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.

Serplat
A: 

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.

Mark Peters
+1  A: 

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

fastcodejava
A: 

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.

Bill K