Created
February 7, 2011 17:33
-
-
Save tebeka/814781 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Map; | |
import java.util.HashMap; | |
public class Make { | |
private Make() {}; | |
@SuppressWarnings(value = "unchecked") | |
public static <K, V> Map<K, V> map(Object... items) { | |
if ((items.length % 2) != 0) { | |
throw new IllegalArgumentException( | |
String.format("Number of items must be even (was %d)", items.length)); | |
} | |
Map<K, V> map = new HashMap<K, V>(); | |
for (int i = 0; i < items.length; i+=2) { | |
map.put((K)(items[i]), (V)(items[i + 1])); | |
} | |
return map; | |
} | |
} | |
class Example { | |
public static void main(String args[]) { | |
Map<String, Integer> m = Make.map("a", 1, "b", 2); | |
for (String key : m.keySet()) { | |
System.out.println(String.format("%s: %d", key, m.get(key))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment