The program will print the incorrect key and value based on the If statement. Can someone explain why?
E.g. Key = Uncle tom + Value = 02086542222 Key = Harry + Value = 020826262
Query = Uncle tom
Returns = Key = Harry + Value = 00826262
Quote from the documentation states below:
"More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))"
So I was under the impression that if(Contacts.containsKey(query)) would compare the input query against the key using key.equals(k)
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class HRHashMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
Map<String, Integer> Contacts = new HashMap<String, Integer>();//Specify HashMap of type String
int numOfContacts = scan.nextInt();
scan.nextLine();
//Add contacts
for (int i = 0; i < numOfContacts; i++) {
String contactName = scan.nextLine();
int contactNumber = scan.nextInt();
scan.nextLine();
Contacts.put(contactName, contactNumber);
}
//Iterate over the Map
for (Entry<String, Integer> entry : Contacts.entrySet()) {
String query = scan.nextLine();
if (Contacts.containsKey(query)) {
//System.out.println(Contacts.get(query));
System.out.println(entry.getKey() + "=" + entry.getValue());
} else {
System.out.println("Not found");
}
}
}
}
Your program iterates over every entry in the map, asking for some input (
query) for each entry, then checks ifqueryis a key in the map and if it is prints the currently visited entry (which is completely unrelated toquery).So the output seems "correct": The map does contain "Uncle Tom", so it proceeds to print the first entry ("Harry"). Note that "first" is a muddy concept in a HashMap, the iteration order of entries is unspecified.
I don't quite understand why you loop over all entries, but the line you commented out (which prints the entry matching
query) may work better: