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);
Given your code doesn’t compile, I can only assume this is not the code you are running.
prints