0

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

1 Answer 1

2

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[].

Sign up to request clarification or add additional context in comments.

2 Comments

In my solution after posting, I detected if odd, recurse on the last element in the kvs array. But I hated the recursion (for seemingly a simple problem.) Would that work? Above answer makes an assumption on key's type.
@foobarometer You can't have an Object[] as a key unless you assume identity. i.e. .equals() won't look at contents. A Object[] as value is more practical.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.