Solved HashMap being picky?

Discussion in 'Plugin Development' started by ItsOneAndTwo, Aug 23, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    ItsOneAndTwo

    So I have stumbled upon this irritating 'bug', I'm saying 'bug', because I might have done something wrong, anyways, lets get on to the problem.

    I have a HashMap, which stores a string and an integer.
    When running this code:
    Code:java
    1. for(Entry<String, Integer> entry : myHashMap.entrySet()) {
    2. if(entry.getKey() == p.getName()) {
    3. myString = myString.replaceAll("%s", entry.getValue() + "");
    4. }
    5. }
    6. p.sendMessage(myString);

    I get this message: "blah blah blah 100", this 100 is actually %s and being replaced by the entry-s value, which is what I need.

    Now if I were to relog, then the %s won't be replaced and I get a message "blah blah blah %s" .

    Any help?
     
  2. Offline

    Necrodoom

    You don't compare String with ==. That checks if they are the same instance. Use equals as for all objects.
     
  3. Offline

    unon1100

    ItsOneAndTwo You should use .equals() rather than ==. There is a difference between the two, and the difference is subtle, but very important.

    Let's say you have your own class, let's call it Example.class, and all it has is a String that it stores, defined as an argument in the constructor.

    == detects if they are the exact same instance
    .equals() detects if they have the same values within the class.
    In our Example...
    Code:java
    1. Example e1 = new Example("a");
    2. Example e2 = e1;
    3. e1 == e2; //returns true
    4. e1.equals(e2); //returns true
    5.  
    6. Example e1 = new Example("b");
    7. Example e2 = new Example("b");
    8. e1 == e2; //returns false
    9. e1.equals(e2); //returns true

    Setting e1 equal to e2 makes it the same exact instance, therefore returning true for ==. BUT, in the second example, == returns false, because even though they have the same values, they are two separate instances.
    Because they have the same values (the string "b") in the second example, .equals will return true.
     
  4. Offline

    ItsOneAndTwo

  5. Offline

    AronTheGamer

    Code:java
    1. for( String key : myHashMap.keySet() )
    2. {
    3. if( key.equals( p.getName() ) )
    4. /// do things with myHashMap.get( key );
    5. }


    My way of doing it
     
Thread Status:
Not open for further replies.

Share This Page