地图<图案 、对象>找不到钥匙图案>
我有以下代码:
List<Pattern> patterns = Lists.newArrayList(Pattern.compile("blah"), Pattern.compile("blah2"));
Map<Pattern, String> map = new HashMap<Patter, String>();
map.put(patterns.get(0), "1");
map.put(patterns.get(1), "2");
Assert.assertTrue(map.containsKey(patterns.get(0)));
断言失败!
为什么会这样呢?首先,令我惊讶的是 Pattern
类没有基于模式实现 equals
和 hashCode
。但即使没有,Object
也不会使用 hashCode
和 equals
的内存地址,这样只要我通过同一个Object
实例,应该找到key了吧?
编辑:抱歉各位。这是我实际拥有的。忘记了每次访问完成时 transform
都会创建一个新实例。
List<Pattern> patterns = Lists.transform(Lists.newArrayList("blah1", "blah2"), toPattern);
I have the following code:
List<Pattern> patterns = Lists.newArrayList(Pattern.compile("blah"), Pattern.compile("blah2"));
Map<Pattern, String> map = new HashMap<Patter, String>();
map.put(patterns.get(0), "1");
map.put(patterns.get(1), "2");
Assert.assertTrue(map.containsKey(patterns.get(0)));
The assert fails!
Why would this be? First, I am surprised that the Pattern
class does not implement equals
and hashCode
based on the pattern. But even if it didn't, doesn't Object
use the memory address for the hashCode
and equals
so that as long as I am passing the same Object
instance, the key should be found?
Edit: Sorry folks. Here is what I actually had. Forgot that transform
will create a new instance each time access is done.
List<Pattern> patterns = Lists.transform(Lists.newArrayList("blah1", "blah2"), toPattern);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
鉴于您的代码无法编译,我只能假设这不是您正在运行的代码。
印刷
Given your code doesn't compile, I can only assume this is not the code you are running.
prints
即使对象没有正确的 hashCode/equals,您仍然可以使用映射和集合。相反,几乎总是可以使用 TreeMap 和自定义比较器:
这里唯一的问题 - 表达正则表达式的真正相等性非常困难。例如,正则表达式“a|b”与“b|a”完全相同。但也许字符串比较对你来说就足够了。
另一种方法是使用所需的 hashCode/equals 将 Pattern 包装在类中,并将其用作哈希映射的键。
You can still use maps and sets, even if objects don't have proper hashCode/equals. Instead it's nearly always possible to use the TreeMap and a custom comparator:
The only problem here - it's quite difficult to express genuine equality of regexps. E.g. regexp "a|b" is exactly the same as "b|a". But maybe string comparison is enough for you.
Yet another way is to wrap the Pattern in your class with desired hashCode/equals and use it as the hash map's key.