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
Java HashMap Litteral Creator
// 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
others.length / 2NOT%