Monday, 29 June 2015

Write HashMap Programme to display basic functionaliy -After adding duplicate keys ,remove etc?

package com.JavaInterview.Programs;

import java.util.*;

/**
 * Find Out Factorial of a number
 * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */
public class HashmapTest {

 public static void main (String args[])
 {
  HashMap String,Integer> h= new HashMap String,Integer>();
 
  /*HashMap String,int> h= new HashMap String,int>();compiler error |You can't use
  primitive types as generic arguments in Java*/
  h.put("abc",12);
  h.put("bcd", 13);
 
  System.out.println("hashmap sample"+h);
 
  //adding duplicates keys
  h.put("abc",14);
  System.out.println("After adding duplicates key"+h);
 
  //adding duplicates value
  h.put("cdf",13);
  System.out.println("After adding duplicates value"+h);
 
  //adding duplicates keys again
  h.put("abc",15);
  System.out.println("Again after adding duplicates key"+h);
 
  //fetch by key
  System.out.println("Fetch map by its value"+h.get("abc"));
  System.out.println("Fetch map by its value"+h.get("bcd"));
 
  //HashMap Empty
  System.out.println("Is HashMap empty "+h.isEmpty());
 
  //remove elements
  h.remove("abc");
  System.out.println("After removal "+h);
 }
}


Output :
hashmap sample{abc=12, bcd=13}
After adding duplicates key{abc=14, bcd=13}
After adding duplicates value{abc=14, bcd=13, cdf=13}
Again after adding duplicates key{abc=15, bcd=13, cdf=13}
Fetch map by its value15
Fetch map by its value13
Is HashMap empty false
After removal {bcd=13, cdf=13}


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...