开发者

Generic HashMap

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?


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜