java - How can I compare the string with the keys in hash map -


i having difficulties compare string (str) keys in hashmap. can see below code, have multiple keys. comparing str keys couldn't values specific key. please note map contains coin.

it works if directly input string eg entry.getkey().getkeyone().tostring().contains("coin")

string str = "coin"; for(map.entry<pair, string> entry : map.entryset()) {     if(entry.getkey().getkeyone().tostring().contains(str)||         entry.getkey().getkeytwo().tostring().contains(str)) {             entry.getvalue();     } }  public class pair {     private string keyone;     private string keytwo;      pair(string one,string two) {         this.keyone=one;         this.keytwo=two;     }      public string getkeyone() {         return keyone;     }      public string getkeytwo() {        return keytwo;     } } 

advice: long using own class pair in map must override equals() , should override hashcode().

you example string literal works, because "coin" in string pool , references same string.

runs here:

public class pair {      private string keyone;     private string keytwo;      pair(string one, string two) {         this.keyone = one;         this.keytwo = two;      }      public string getkeyone() {         return keyone;     }      public string getkeytwo() {         return keytwo;      }      public static void main(string[] args) {         map<pair, string> map = new hashmap();         map.put(new pair("coin", "5"), "u");         map.put(new pair("bill", "100"), "h");         map.put(new pair("10", "5coin"), "t");          string str = new string("coin");         (map.entry<pair, string> entry : map.entryset()) {             if (entry.getkey().getkeyone().tostring().contains(str)                     || entry.getkey().getkeytwo().tostring().contains(str)) {                 system.err.println(entry.getvalue());             }         }     } } 

Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

arrays - Algorithm to find ideal starting spot in a circle -