Search code examples
javadictionaryencapsulation

Encapsulation: why the name keySet in java


In java to get all the keys in a map we can use the method keySet. But I was wondering why the method name is not just keys? isn't the name Set leaks details about the implementation?

As per my understanding Java is statically typed language and having types in names makes no sense at all. The calling code anyways must have the correct interface type. If we assume that this strategy is correct then every method must have types prefixed to them which doesn't makes any sense. I think @JBNizet stated correctly in his comment the reason behind the choice.


Solution

  • I was wondering why the method name is not just keys

    Like so many things in modern Java, backwards compatibility got in the way a bit: keys() was already taken (by java.util.Hashtable.keys(), and that class should still be able to implement Map), so they had to choose something else.

    Doesn't the name Set leaks details about the implementation ?

    No, it does not. The Map interface already specifies that there cannot be duplicate keys. So the collection of keys is a Set by definition. And Set is still an interface for which there can be different implementations.