0

I have one method, check which has two hashmaps as parameters. Keys of these maps is a String and value is String or Arraylist.

Which is the better solution:

public static boolean check(HashMap<String, ?> map1, HashMap<String, ?> map2) {
    for ( entry <String, ? > entry : map1.entryset()) {
        ...
    }
}

or

public static <V> boolean check(HashMap<String, V> map1, HashMap<String, V> map2) {
    for ( entry <String, V > entry : map1.entryset()) {
        ...
    }    
}

and why?

And can you also give me some more information about the difference between these two solutions?

2 Answers 2

5

In the first, the ? coul dbe anything. One could be <String, String> the other could be <String, Double>. In the second option they must be the same.

Now the first is acceptable as long as you have the ability to convert them so they're comparable. For example, you could do .toString() on both values to compare. But personally, I would prefer the second as it allows me to have more control over what's going on, and gives me compile time checking of types.

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

Comments

0

The second one enforces at compile-time that the two maps are parameterised the same as each other. It also allows you do something useful with the maps, such as inserting non-null elements into them (this isn't possible with wildcards).

Comments

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.