通用哈希映射

发布于 2024-12-04 04:55:20 字数 608 浏览 1 评论 0原文

我有一种方法,check,它有两个哈希图作为参数。这些映射的键是String,值是StringArraylist

哪个是更好的解决方案:

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

或者

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

为什么?

您能否提供更多有关这两种解决方案之间差异的信息?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

习惯成性 2024-12-11 04:55:20

在第一个中,?可以是任何东西。一个可以是,另一个可以是。在第二个选项中,它们必须相同。

现在,只要您有能力转换它们以使它们具有可比性,第一个是可以接受的。例如,您可以对两个值执行 .toString() 进行比较。但就我个人而言,我更喜欢第二种,因为它允许我更好地控制正在发生的事情,并让我可以在编译时检查类型。

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.

静水深流 2024-12-11 04:55:20

第二个在编译时强制两个映射的参数化彼此相同。它还允许您对映射执行一些有用的操作,例如向其中插入非 null 元素(这对于通配符是不可能的)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文