RFR: 8293630: Simplify TreeMap.get() with Comparator.naturalOrder()
ExE Boss
duke at openjdk.org
Thu Oct 13 21:49:23 UTC 2022
On Sat, 20 Aug 2022 19:17:18 GMT, Сергей Цыпанов <duke at openjdk.org> wrote:
>> src/java.base/share/classes/java/util/TreeMap.java line 3318:
>>
>>> 3316: // Adapt or create a key-based comparator
>>> 3317: Comparator<? super K> treeComparator = tree.comparator;
>>> 3318: return Map.Entry.comparingByKey(treeComparator == null ? natural() : treeComparator);
>>
>> You can probably have:
>>
>> return treeComparator == nul ?
>> Map.Entry.comparingByKey() :
>> Map.Entry.comparingByKey(treeComparator);
>>
>> instead.
>
> Nope, there'd be a compilation error
It'll work fine if an unchecked cast is used:
Suggestion:
@SuppressWarnings("unchecked")
Comparator<Map.Entry<K, V>> entryComparator = treeComparator == null ?
(Comparator) Map.Entry.comparingByKey()
Map.Entry.comparingByKey(treeComparator);
return entryComparator;
This also ensures that when `treeComparator` is `null`, this method keeps returning a constant lambda.
-------------
PR: https://git.openjdk.org/jdk/pull/9901
More information about the core-libs-dev
mailing list