How can I use contains method on a list that contains HashMaps so that it returns true when I ask whether or not the list contains a specified HashMap
For Example:
List ssibenefit = new ArrayList();
HashMap map = new HashMap();
map.put("one", "1");
ssibenefit.add(map);
HashMap map4 = new HashMap();
map4.put("one", "1");
System.out.println("size: " + ssibenefit.size());
System.out.println("does it contain orig: " + ssibenefit.contains(map));
System.out.println("does it contain new: " + ssibenefit.contains(new HashMap().put("one", "1")));
should return:
size: 1
does it contain orig: true
does it contain new: true
but in this case the actual output is
size: 1
does it contain orig: true
does it contain new: false
Update
Sorry, I’ve updated the question. As I was posting the question, I realized what I wanted to do and what I was asking were not the same thing.
I’m afraid the answers you’ve been given so far (prior to Vlad’s answer) are all complete rubbish (which is surprising, because this is pretty basic stuff!).
The reason your test prints
falsewhere you would like to seetrueis thatput("one", "1")returns the previous value of the mapping, not the map you’ve just manipulated. So, your call tossibenefit.containsis asking if the list containsnull. Which it doesn’t.On the other hand, if you rewrite your test:
You will see that it prints true.
If you read the javadoc for List.contains, you’ll see that it
So, it works by equality, not identity, as others have asserted. And if you read the javadoc for Map.equals, you’ll see that it
So, equality is defined as equality of content, not identity. Putting those two together, you can see that what you’re trying to do must work on any compliant implementation of Java.