简体   繁体   English

通用HashMap

[英]Generic HashMap

I have one method, check which has two hashmaps as parameters. 我有一种方法, check其中有两个哈希图作为参数。 Keys of these maps is a String and value is String or Arraylist . 这些映射的键是String ,值是StringArraylist

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> . 一个可能是<String, String> ,另一个可能是<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. 例如,您可以对两个值都使用.toString()进行比较。 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). 它还允许您对映射进行一些有用的操作,例如将非null元素插入到映射中(通配符无法实现)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM