Generifying toMap() method (adding in possibility for type inference on return type).

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@983137 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
James W. Carman 2010-08-06 22:44:38 +00:00
parent 823f2603a4
commit e7f8d9bbfb
1 changed files with 6 additions and 4 deletions

View File

@ -16,6 +16,7 @@
*/
package org.apache.commons.lang3;
import java.awt.Color;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
@ -222,16 +223,17 @@ public class ArrayUtils {
* @throws IllegalArgumentException if the array contains elements other
* than {@link java.util.Map.Entry} and an Array
*/
public static Map<Object, Object> toMap(Object[] array) {
@SuppressWarnings("unchecked")
public static <K,V> Map<K, V> toMap(Object[] array) {
if (array == null) {
return null;
}
final Map<Object, Object> map = new HashMap<Object, Object>((int) (array.length * 1.5));
final Map<K, V> map = new HashMap<K, V>((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Object object = array[i];
if (object instanceof Map.Entry<?, ?>) {
Map.Entry<?,?> entry = (Map.Entry<?,?>) object;
map.put(entry.getKey(), entry.getValue());
map.put((K)entry.getKey(), (V)entry.getValue());
} else if (object instanceof Object[]) {
Object[] entry = (Object[]) object;
if (entry.length < 2) {
@ -239,7 +241,7 @@ public class ArrayUtils {
+ object
+ "', has a length less than 2");
}
map.put(entry[0], entry[1]);
map.put((K)entry[0], (V)entry[1]);
} else {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object