DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Java HashMap Litteral Creator

11.13.2009
| 3269 views |
  • submit to reddit
        // Here is a nice helper to create on the fly litteral hashmap.
// this makes use of Java 1.5 generic methods / class parametrization. 
//
// Example of usage :
//    
// import static Utils.*
// 
// ... 
// 
// HashMap<String, Integer> = map("toto", 2, "titi", 3)
//
//

class Utils {

    /** Create a quick litteral map */
    public static <K, V> HashMap<K, V> map(K key1, V val1, Object ... others) {
        
        // Create result hashmap
        HashMap<K, V> map = new HashMap<K, V>();
        
        // Add first key/val pair
        map.put(key1, val1);
        
        // Check number of args
        if (others.length % 2 != 0) throw new Error("There should be a even number of arguments");
        
        // Loop on pairs
        for (int i=0; i < others.length % 2; i++) {
            
            // Get key / val
            K key = (K) others[2*i];
            V val = (V) others[2*i + 1];
            
            // Add it to the map
            map.put(key, val);
          
            
        } // End of loop on pairs
        
        return map;    
    }
}    

Comments

Jayaprakash Velimala replied on Sun, 2009/11/15 - 11:41am

cool Idea. :) Just a small correction.. While looping on pairs.. it should be others.length / 2 NOT %