package mightypork.utils.objects;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Varargs parser
* Converts an array of repeated "key, value" pairs to a LinkedHashMap.
* example:
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* Object[] array = { "one", 1, "two", 4, "three", 9, "four", 16 };
* Map<String, Integer> args = new VarargsParser<String, Integer>().parse(array);
*
*
* @author MightyPork
* @param Type for Map keys
* @param Type for Map values
*/
public class VarargsParser {
/**
* Parse array of vararg key, value pairs to a LinkedHashMap.
*
* @param args varargs
* @return LinkedHashMap
* @throws ClassCastException in case of incompatible type in the array
* @throws IllegalArgumentException in case of invalid array length (odd)
*/
@SuppressWarnings("unchecked")
public Map parse(Object... args) throws ClassCastException, IllegalArgumentException
{
LinkedHashMap attrs = new LinkedHashMap();
if (args.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of elements in varargs map!");
}
K key = null;
for (Object o : args) {
if (key == null) {
if (o == null) throw new RuntimeException("Key cannot be NULL in varargs map.");
key = (K) o;
} else {
attrs.put(key, (V) o);
key = null;
}
}
return attrs;
}
}