Reputation: 1519
Please explain output of below code. I guessed it null , because command line arguments are different than its key. But it is not correct explanation. It is null because friends class doesnot override equals and hashcode() methods.
But why?
import java.util.*;
public class Birthdays {
public static void main(String[] args) {
Map<Friends, String> hm = new HashMap<Friends, String>();
hm.put(new Friends("Charis"), "Summer 2009");
hm.put(new Friends("Draumur"), "Spring 2002");
Friends f = new Friends(args[0]);
System.out.println(hm.get(f));
}
}
class Friends {
String name;
Friends(String n) { name = n; }
}
And the command line invocation: java Birthdays Draumur
Upvotes: 0
Views: 730
Reputation: 27672
args[0]
will contain the string "Draumur"
, so that is not the reason for the program printing null
.
A HashMap
is a hash table, and it finds elements in it based on the hash value of the key. If you don't override the hash method, Java will calculate the hash value based on the object identity, so two different Friends
objects, even with the same name
inside, will not be guaranteed to hash to the same value.
You would also need to write an equals
method, since if you don't override it, Java will also consider two different Friends
objects not to be equal, even with the same name
inside.
In summary, you need to override the hashCode
method so the HashMap
can find the Friends
object, and you need to override the equals
method so the HashMap
, when it has found it, can see that it is the object it is searching for.
Here is a possible new version of the Friends
class (and I would also suggest you call it Friend
, since one such object represents one single friend):
class Friends {
String name;
Friends(String n) { name = n; }
public boolean equals(Object o) {
if (!(o instanceof Friends))
return false;
Friends rhs = (Friends)o;
return (name.equals(rhs.name));
}
public int hashCode() {
return name.hashCode();
}
}
Upvotes: 1
Reputation: 4753
The get
method of a map return the value of the key
where map key ".equals" to researched key
Your Friends key do not implements equals
, so the default one from Object
is used, which is a "==" compare (true only if it is the same object).
Get
will only give you something if you use the exact same object you put
as key.
Upvotes: 0
Reputation: 192043
command line arguments are different than its key
Not sure I understand that logic...
args = {"Draumur"}
new Friends(args[0]) = new Friends("Dramur")
A key like that was placed in the map already, but a Friend is not comparable to other Friend objects via a hashcode or equality otherwise.
If you had a HashMap of String to String, then get("Dramur")
would not be null.
Upvotes: 0