Last active
December 11, 2015 08:59
-
-
Save shunirr/4577191 to your computer and use it in GitHub Desktop.
This file contains 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
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; | |
} | |
} |
This file contains 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
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