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:
parent
823f2603a4
commit
e7f8d9bbfb
|
@ -16,6 +16,7 @@
|
||||||
*/
|
*/
|
||||||
package org.apache.commons.lang3;
|
package org.apache.commons.lang3;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
import java.lang.reflect.Array;
|
import java.lang.reflect.Array;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
@ -222,16 +223,17 @@ public class ArrayUtils {
|
||||||
* @throws IllegalArgumentException if the array contains elements other
|
* @throws IllegalArgumentException if the array contains elements other
|
||||||
* than {@link java.util.Map.Entry} and an Array
|
* 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) {
|
if (array == null) {
|
||||||
return 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++) {
|
for (int i = 0; i < array.length; i++) {
|
||||||
Object object = array[i];
|
Object object = array[i];
|
||||||
if (object instanceof Map.Entry<?, ?>) {
|
if (object instanceof Map.Entry<?, ?>) {
|
||||||
Map.Entry<?,?> entry = (Map.Entry<?,?>) object;
|
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[]) {
|
} else if (object instanceof Object[]) {
|
||||||
Object[] entry = (Object[]) object;
|
Object[] entry = (Object[]) object;
|
||||||
if (entry.length < 2) {
|
if (entry.length < 2) {
|
||||||
|
@ -239,7 +241,7 @@ public class ArrayUtils {
|
||||||
+ object
|
+ object
|
||||||
+ "', has a length less than 2");
|
+ "', has a length less than 2");
|
||||||
}
|
}
|
||||||
map.put(entry[0], entry[1]);
|
map.put((K)entry[0], (V)entry[1]);
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("Array element " + i + ", '"
|
throw new IllegalArgumentException("Array element " + i + ", '"
|
||||||
+ object
|
+ object
|
||||||
|
|
Loading…
Reference in New Issue