Skip to content

Instantly share code, notes, and snippets.

@cristobalmoralesm
Forked from shunirr/MapBuilder.java
Last active September 15, 2015 17:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristobalmoralesm/84c2f1f8276a84a82048 to your computer and use it in GitHub Desktop.
Save cristobalmoralesm/84c2f1f8276a84a82048 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