通用哈希映射
我有一种方法,check
,它有两个哈希图作为参数。这些映射的键是String
,值是String
或Arraylist
。
哪个是更好的解决方案:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一个中,?可以是任何东西。一个可以是
,另一个可以是
。在第二个选项中,它们必须相同。现在,只要您有能力转换它们以使它们具有可比性,第一个是可以接受的。例如,您可以对两个值执行
.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.第二个在编译时强制两个映射的参数化彼此相同。它还允许您对映射执行一些有用的操作,例如向其中插入非
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).