Skip to content

Instantly share code, notes, and snippets.

@shunirr
Last active December 11, 2015 08:59
Show Gist options
  • Save shunirr/4577191 to your computer and use it in GitHub Desktop.
Save shunirr/4577191 to your computer and use it in GitHub Desktop.
package jp.s5r;
import java.util.HashMap;
import java.util.Map;
public class MapBuilder<K, V> {
private Object[] objects;
public MapBuilder(Object[] args) {
if (args.length % 2 != 0) {
throw new IllegalArgumentException();
}
objects = args;
}
public Map<K, V> build() {
Map<K, V> map = new HashMap<K, V>();
for (int i = 0; i < objects.length; i += 2) {
map.put((K)objects[i], (V)objects[i + 1]);
}
return map;
}
}
package jp.s5r;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, Integer> map =
new MapBuilder<String, Integer>(new Object[] {
"hoge", 10,
"fuga", 20,
"hahe", 30
}).build();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(
"key: " + entry.getKey() + ", " + "value: " + entry.getValue()
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment