Domanda

I want to use a better constructor for HashMap so I wrote one like this:

public static Map<S, T> newMap(S obj1, T obj2, Object... objects) {
    h = new HashMap<S, T> ();
    h.put(obj1, obj2);
    ... // parse object and put it in h.
}

My problem is I have few methods that take variadic arguments themselves and transfer the arguments to the newMap method.

For example,

public static void foo(S arg0, T arg1, Object... kv) {
    ...
    newMap(tmp0, tmp1, kv); // WRONG: kv is an array and not a variadic transfer.
}

and called as:

foo(arg0, arg1, key1, val1, key2, val2);

This works fine but, when the call to newMap is:

newMap(tmp0, tmp1, tmp2, tmp3, kv);

and call to foo is

foo(arg0, arg1)

then the empty array [] sits in kv. Which creates problems with parsing, because we now have uneven number of elements in the "objects" array.

 objects = { tmp2, tmp3, [] }

Can this be done without walking through the arguments in the kv object array and reconstructing an array with all objects [tmp0, tmp1, tmp2, tmp3] for the newMap call.

Refer: Better Map Constructor

È stato utile?

Soluzione

You can do this instead.

public static <K, V> Map<K, V> newMap(K key1, V value1, Object... kvs) {
    Map<K, V> m = new HashMap<>();
    m.put(key1, value1);
    addToMap(map, kvs);
    return m;
}

private static <K, V> void addToMap(Map<K,V> map, Object[] kvs) {
    for(int i = 0; i < kvs.length; i++) {
        Object key = kvs[i];
        if (key instanceof Object[]) {
           addToMap(map, (Object[]) key);
        } else if (++i < kvs.length) {
           map.put((K) key, (V) kvs[i]);
        }
    }
}

This will unpack nested Object[] if they are "keys", if they are "values" they will remain as Object[].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top