Turtle programming game that was never finished to a playable state (but had cute graphics and sounds)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tortuga/src/com/porcupine/util/VarargsParser.java

54 lines
1.4 KiB

package com.porcupine.util;
import java.util.LinkedHashMap;
/**
* Varargs parser<br>
* Converts an array of repeated "key, value" pairs to a LinkedHashMap.<br>
* example:
*
* <pre>
*
* Object[] array = { &quot;one&quot;, 1, &quot;two&quot;, 4, &quot;three&quot;, 9, &quot;four&quot;, 16 };
* Map&lt;String, Integer&gt; args = new VarargsParser&lt;String, Integer&gt;().parse(array);
* </pre>
*
* @author Ondřej Hruška (MightyPork)
* @param <K> Type for Map keys
* @param <V> Type for Map values
*/
public class VarargsParser<K, V> {
/**
* 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 LinkedHashMap<K, V> parse(Object... args) throws ClassCastException, IllegalArgumentException
{
LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>();
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;
}
}