1

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
1
  • 3
    What would you expect? You will see the same with any single non-null object too. Equal values are (obviously) treated differently by list and map, that's all. Commented Mar 21, 2012 at 6:43

4 Answers 4

9

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?

Sign up to request clarification or add additional context in comments.

Comments

2

Because a Map can only have unique key. In this case it's a null

put(null, null);
put(null, null);
put(null, null);

Previous statements are actually overwriting the value after the first call. That's why the size remain 1

1 Comment

+1. Has nothing to do with null, really. Same thing would happen with add("a")
1

Java documentation states:

If the map previously contained a mapping for the key, the old value is replaced

The bar:1 is entirely correct.

Comments

0

HashMap won't allow you to store values with duplicate keys(your value null in this case). That's the reason why the size is "1" in the second case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.