Feature suggestion: Provide efficient way for nullable value lookup in Map
Brian Goetz
brian.goetz at oracle.com
Tue Jan 8 20:32:28 UTC 2019
Usually when we add defaults to Collection interfaces, we provide
efficient implementations for the several dozen primary JDK
implementations.
On 1/8/2019 11:16 AM,
some-java-user-99206970363698485155 at vodafonemail.de wrote:
> Would this method then be useful enough if the default implementation is that inefficient (in case
> you only want to get a nullable value)?
>
>> Brian Goetz <brian.goetz at oracle.com> hat am 8. Januar 2019 um 16:57 geschrieben:
>>
>>
>> Here's a default implementation that returns the actual key:
>>
>> default Optional<Map.Entry<K,V>> getEntry(K key) {
>> for (Map.Entry<K,V> e : entrySet) {
>> if (Objects.equals(key, e.getKey())
>> return Optional.of(e);
>> }
>> return Optional.empty();
>> }
>>
>> On 1/8/2019 10:50 AM,
>> some-java-user-99206970363698485155 at vodafonemail.de wrote:
>>> Yes it is now possible to implement the methods `getKey(Object key)` and `getEntry(Object key)`
>>> requested by JDK-6552529 as default methods, however both would have to include that
>>> "The default implementation returns the provided key. Overriding implementations may return the
>>> actual key used by the map."
>>> In this case it is questionable how useful the methods actually are, e.g.
>>> Two key objects k1 and k2 with `k1.equals(k2)`
>>> Two objects m1 and m2 of different map implementations both containing k1.
>>> Then the following is possible:
>>> m1.getKey(k2) == k2 // true
>>> m2.getKey(k2) == k2 // false
>>>
>>>> Brian Goetz <brian.goetz at oracle.com> hat am 7. Januar 2019 um 00:54 geschrieben:
>>>>
>>>>
>>>> FYI, the comment about compatibility was obsoleted by the addition of
>>>> default methods in Java 8.
More information about the core-libs-dev
mailing list