HashMap questions

Discussion in 'Plugin Development' started by Assist, Aug 25, 2013.

Thread Status:
Not open for further replies.
  1. I'm quite disappointed at the lack of my java knowledge.

    Tried asking this @stackoverflow, got nothing but directions to HashMap documentation.

    Anyways, if I have a hashmap like this
    Code:
    public HashMap<String, String> map = new HashMap<String, String>();
    Which one of the Strings is the key? I always thought the key is the first one.. but I was told differently.

    Now if I want to add something to that map, in my case, a key and player name, would I do it this way:
    Code:
    map.put(key, value);
    or
    Code:
    map.put(value, key);
    Eclipse tells me the first way, but people at stackoverflow tell me the second way. If want to store players, I always did it this way
    Code:
    map.put(someKey, player.getName());
    then loop through the map with key 'someKey', then it would retrieve the names.

    If I want to retrieve all the strings in the map, I do it this way
    Code:
    for(String str : map.get(key)) { }
    Now would that retrieve the first String or the second String?

    I came up with this question while I was writing a plugin a while ago. I wanted to remove a value from hashmap depending on the key. I have no idea how to do this. I wrote this, but have no idea if it would work.
    Code:
    public void remove(String id, Player user) {
        for (Entry < String, String > entry: map.entrySet()) {
            if (entry.getKey() == id && entry.getValue() == user.getName()) {
                entry.setValue(null);
            }
        }
    }
    So the main question here is, if I want to store multiple strings/whatever to a map with key, do I use String, or List<String> (or something similar)?
     
  2. Offline

    CubieX

    The first parameter is the "key" and the second is the "value" for this key.

    If you want to store multiple values behind one key, you can use an ArrayList<String> as value for example.
    Or a Set<String>, or whatever collection will fit your needs best.
    Accessing single objects behind the key will be a bit more complicated then,
    but if you need a unique key for those values, this is what you can do.

    But beware: If you want to delete a key while iterating over the HashMap, you either need to use an "Iterator" for it, or (not 100% sure about that) you could use a "ConcurrentHashMap".
    otherwise you will run into a "ConcurrentModuificationException".
     
  3. If you are not sure, always take a look at the javadocs. The javadocs are always (well would be bad if they weren't) right.
     
Thread Status:
Not open for further replies.

Share This Page