HashMap:
- HashMap is collection that stores elements in the form of key-value pairs.
- If key provided later its corresponding value can be easily retrieved from the HashMap .
- Duplicate keys are not allowed but values can be duplicated
- Insertion order is not preserved and it is based on hashcode of the keys.
- Heterogeneous objects are allowed for key and value
- Null allowed for the key(only once) and for values(any number of)
- It is not Synchronized.but we can synchronized by using method of collection class
public staic Map synchronizedMap(Map m);
Constructors:
- HashMap m=new HashMap();//creates an empty HashMap object with default initial capacity 16 and default fill ratio 0.75 .fill ratio is also known as Load Faction
- HashMap m=new HashMap(Map m);
- HashMap m=new HashMap(int initialcapacity);
- HashMap m=new HashMap(int initialcapacity float fillratio);
HashMapExample
import java.util.Collection;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
//create HashMap object
HashMap hMap = new HashMap();
//add key value pairs to HashMap
hMap.put(1,"One");
hMap.put(2,"Two");
hMap.put(3,"Three");
hMap.put(4,"four");
hMap.put(5,"five");
Set st = hMap.keySet();//get the keys
System.out.println("get the keys");
Iterator itr = st.iterator();
while(itr.hasNext())
System.out.println(itr.next());
System.out.println("get the values");
Collection c = hMap.values();
//obtain an Iterator for Collection
Iterator itr1 = c.iterator();
//iterate through HashMap values iterator
while(itr1.hasNext())
System.out.println(itr1.next());
}
}
import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
//create HashMap object
HashMap hMap = new HashMap();
//add key value pairs to HashMap
hMap.put(1,"One");
hMap.put(2,"Two");
hMap.put(3,"Three");
hMap.put(4,"four");
hMap.put(5,"five");
Set st = hMap.keySet();//get the keys
System.out.println("get the keys");
Iterator itr = st.iterator();
while(itr.hasNext())
System.out.println(itr.next());
System.out.println("get the values");
Collection c = hMap.values();
//obtain an Iterator for Collection
Iterator itr1 = c.iterator();
//iterate through HashMap values iterator
while(itr1.hasNext())
System.out.println(itr1.next());
}
}
output:
get the keys:
1
2
3
4
5
get the values
One
Two
Three
four
five
No comments:
Post a Comment