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.
59 lines
1.4 KiB
59 lines
1.4 KiB
11 years ago
|
package mightypork.utils.objects;
|
||
|
|
||
|
|
||
|
import java.util.LinkedHashMap;
|
||
|
import java.util.Map;
|
||
|
|
||
|
|
||
|
/**
|
||
|
* Varargs parser<br>
|
||
|
* Converts an array of repeated "key, value" pairs to a LinkedHashMap.<br>
|
||
|
* example:
|
||
|
*
|
||
|
* <pre>
|
||
|
*
|
||
|
*
|
||
|
*
|
||
|
*
|
||
|
* Object[] array = { "one", 1, "two", 4, "three", 9, "four", 16 };
|
||
|
* Map<String, Integer> args = new VarargsParser<String, Integer>().parse(array);
|
||
|
* </pre>
|
||
|
*
|
||
|
* @author 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 Map<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;
|
||
|
}
|
||
|
}
|