What if we change it to:

public static <K,V> Map<K, V> toMap(Object[] array)

Then, you can use type inference so you don't have to do any casting!

On Fri, Aug 6, 2010 at 4:54 PM, Shekhar Gulati
<shekhargulat...@gmail.com> wrote:
> Hello,
>
> I have started playing with latest beta release of Commons-Lang 3.0  and I
> have question on usage of generics in Commons-lang
>
> For example, there is a method called toMap in ArrayUtils which could have
> been easily generified but isn't
>
> In Commons-Lang 3.0
>
> public static Map<Object, Object> toMap(Object[] array) {
>        if (array == null) {
>            return null;
>        }
>        final Map<Object, Object> map = new HashMap<Object, Object>((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());
>            } else if (object instanceof Object[]) {
>                Object[] entry = (Object[]) object;
>                if (entry.length < 2) {
>                    throw new IllegalArgumentException("Array element " + i
> + ", '"
>                        + object
>                        + "', has a length less than 2");
>                }
>                map.put(entry[0], entry[1]);
>            } else {
>                throw new IllegalArgumentException("Array element " + i + ",
> '"
>                        + object
>                        + "', is neither of type Map.Entry nor an Array");
>            }
>        }
>        return map;
>    }
>
>
>
> Fully Generified version of toMap method
>
> public static <T> Map<T, T> toMap(T[][] array) {
> if (array == null) {
> return null;
> }
> final Map<T, T> map = new HashMap<T, T>((int) (array.length * 1.5));
> for (int i = 0; i < array.length; i++) {
> T[] t = array[i];
> if (t[i] instanceof Map.Entry) {
> @SuppressWarnings("unchecked")
> Map.Entry<T, T> entry = (Map.Entry<T, T>) t[i];
> map.put(entry.getKey(), entry.getValue());
> } else if (t instanceof Object[]) {
> T[] entry = t;
> if (entry.length < 2) {
> throw new IllegalArgumentException("Array element " + i
> + ", '" + t + "', has a length less than 2");
> }
> map.put(entry[0], entry[1]);
> } else {
> throw new IllegalArgumentException("Array element " + i + ", '"
> + t + "', is neither of type Map.Entry nor an Array");
> }
> }
> return map;
> }
>
> I just thought to ask the Commons-Lang team.. Are there any reason why some
> methods are not generified?
>
>
>
>
> --
> Thanks
> Shekhar
> 09873937317
>

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org
For additional commands, e-mail: dev-h...@commons.apache.org

Reply via email to