When I write
String str1 = new String("hello");
String str2 = new String("hello");
afaik, even though the String contents are same, str1 and str2 will point to separate memory location as it will refer in heap and not in pool.
In this case, when I execute the below program, why is it giving me the value when the two instances (Key) of string are different? then why the same is not happening with user defined objects?
String str1 = new String("hello");
String str2 = new String("hello");
AB obj1 = new AB();
BC obj2 = new BC();
HashMap h = new HashMap();
h.put(str1, "data");
h.put(obj1, "data1");
System.out.println(h.get(str2));
System.out.println(h.get(obj2));
class AB {
int code = 10;
}
class BC {
int code = 10;
}
Output:
data
null
Because HashMap will first find the correct bucket based on the hashcode of the string object.Once it finds the bucket, after that it will invoke the Equals method to compare the key.
Ps note that Equals comparions is overriden by String class hence it compares not just on the basis of reference but based on content.