Switch to full style
Java Collections classes examples .
Post a reply

HashMap class with generics

Mon Dec 28, 2009 7:58 pm

HashMap class with generics :
In this example . we see how we reverse the key and value .
Code:

import java
.util.HashMap;
import java.util.Map;

public class 
TestHashMap {

    public static 
void main(String args[])
    {
    
    
TestHashMap hashMap = new TestHashMap();
    
    
HashMap<String,IntegeroldhashMap = new HashMap<StringInteger>();
    
oldhashMap.put("a",1);
    
oldhashMap.put("2"2);
    
    
HashMap<Integer,String>  map hashMap.copyHashMap(oldhashMap);
    
System.out.println("Value of key =1 is : "+map.get(1));
    
    }
    
    public <
VKHashMap<VKcopyHashMap(HashMap<K,VoldhashMap)
    {
    
HashMap<VKnewhashMap = new HashMap<V,K>();
    
    for(
Map.Entry<KVentry :oldhashMap.entrySet())
    {
        
newhashMap.put(entry.getValue(),entry.getKey());
    }
    
    return  
newhashMap;
    }
}
 


The output is :
Value of key =1 is : a



Post a reply
  Related Posts  to : HashMap class with generics
 How to use Generics in java     -  
 How to use Generics and implement it in Java     -  
 how to show hashmap value in a textbox     -  
 Print the content of hashMap object     -  
 Define class helper class to check the method existance     -  
 java abstract class,concrete class and interface     -  
 relationship between the Canvas class and the Graphics class     -  
 inner class that is a member of an outer class?     -  
 Define class inside another class C++     -  
 load class to applet- load frame class to applet     -  

Topic Tags

Java Collections