Professional Documents
Culture Documents
Instructor Name:
Lecture-11
Today’s Lecture
HashMap
2
MAP
One difference between the ArrayList and a Map is that with a Map
each entry is not an object, but a pair of objects.
3
MAP
A telephone directory contains entries, and each entry is a pair: a name and a
phone number.
You use a phone book by looking up a name and getting a phone number.
We do not use an index—the position of the entry in the phone book—to find
it.
A map can be organized in such a way that looking up a value for a key is
easy. In the case of a phone book, this is done using alphabetical sorting.
By storing the entries in the alphabetical order of their keys, finding the key
and looking up the value is easy
4
HashMap
Using HashMap
HashMap is a particular implementation of Map.
The most important methods of the HashMap class are put and get.
5
HashMap
Using HashMap
The following code fragment creates a HashMap and inserts three entries into
it. Each entry is a key/value pair consisting of a name and a telephone
number.
HashMap<String, String> phoneBook = new HashMap<String, String>();
The following code will find the phone number for Atif Ishaq and print it.
System.out.println(number); 6
HashMap
phonebook.put(name,number);
7
HashMap
HashMapTester Class
import java.util.Scanner;
public class HashMapTester
{
public static void main(String[] args){
PhoneBook phonebook=new PhoneBook();
Scanner sc=new Scanner(System.in);
String opt="Y";
do{
System.out.print("Enter Name : ");
String name=sc.next();
System.out.print("Enter Number : ");
String number=sc.next();
phonebook.enterNumber(name,number);
System.out.print ("Do you want to add more Numbers : ");
opt=sc.next();
}while(opt.equals("Y"));
}
} 8
HashMap
If a Key already exists, it will replace its value with new value.
It will replace the phone number 7777 777 with 6666 777 against the key
if(phonebook.containsKey(name))
phonebook.remove(name);
else
System.out.println("Invalid Entry");
10
HashMap
11
HashSet
12
Collections
13
14