I was trying to do an exercise creating a PhoneBook
using HashMap
.
However I see my addPhone
method doesn't add a new phone to my PhoneBook
pb
i.e. data.put(name, num);
method inside my addPhone
doesn't put the data into the HashMap
data
.
Can somebody explain me what is wrong here?
UPD
Now I understand it was a mistake, I used containsValue
method instead of containsKey
. So simple!
But this question is not similar at all to the suggested already existing question. I was not asking Is checking for key existence in HashMap always necessary?
I know about the ways to search the HashMap
according to the key or to the value. This question is actually caused by a mistake. However I received a very wide and useful answers here. I believe these answers, especially davidxxx's answer is excellent and may be useful for many people.
import java.util.HashMap;
public class PhoneBook {
private HashMap<String, String> data;
public PhoneBook()
{
data = new HashMap<String, String>();
}
public void addPhone(String name, String num)
{
data.put(name, num);
}
//a
public String getPhone(String name){
if(data.containsValue(name)){
return data.get(name);
}
else
return null;
}
//b
public void ToString(){
data.toString();
}
public static void main(String[] args) {
PhoneBook pb = new PhoneBook();
pb.addPhone("shlomi", "12312413yuioyuio24");
pb.addPhone("shlomi1", "1231345345241324");
pb.addPhone("shlomi2", "12312445735671324");
System.out.println(pb.getPhone("shlomi"));
System.out.println(pb.getPhone("blat"));
pb.ToString();
}
}