What can be rational for below output ?
null elements are treated differently by list and map.
List<Object> hoo = new ArrayList<Object>() {
{
add(null);
add(null);
}
};
Map<Object, Object> bar = new HashMap<Object, Object>() {
{
put(null, null);
put(null, null);
put(null, null);
}
};
System.err.println("hoo:" + hoo.size());
System.err.println("bar:" + bar.size());
Output:
hoo:2
bar:1
Concretely : Lists can have duplicate items, but maps can’t have duplicate keys, which is why we can have 2 nulls in a list but only one null in a map.
The answer to your more general question (the logic of how these interfaces behave regarding duplicates), is that there is not any one “more” or “less” logical way to implement null constraints in maps.
Certainly, there is no universal rule : for example –
Originally, java’s Hashtables did not allow for null values.
But later, the HashMap implemented a different behaviour (allows null values).
Since the real world certainly has instances where we can have null values, but there are very few instances where we would / should have a null key, you might ask your self why you have multiple entries with a null key and null value in the same data structure – do these values actually represent anything meaningful?