On Wed, 16 Mar 2022 at 14:42, Matt Juntunen <matt.a.juntu...@gmail.com>
wrote:

> Hello,
>
> > I suggest to carefully consider whether to return a "SimpleEntry"
> (and prominently note that any sort of concurrent modification is
> a caller responsibility).
>
> I see what you mean and I think that would be a good idea. However,
> the sticking point is that the 1D implementations for both Euclidean
> and spherical space internally use the JDK's TreeMap class to store
> entries, due to its superior performance when compared to the
> AbstractBucketPointMap class used for other dimensions. TreeMap
> returns immutable Map.Entry instances from its entry-access methods
> (e.g., ceilingEntry, floorEntry), so there is not a straightforward
> way for us to implement the behavior you propose for these dimensions.
> The options I see are:
> 1. Have all returned entries be immutable (the current behavior).
> 2. Return specialized Map.Entry implementations for the 1D cases that
> call the "put" method on the underlying map when "setValue" is called.
>
> Option #2 seems less than ideal so unless there is another approach
> that I'm missing, I vote for #1.
>
>
Option #3

Since the 1D TreeMap is hidden, you store entries in it as an
updatable reference, e.g. 'new Object[1]'. You can then get the immutable
entry from the TreeMap and update the contents stored in the immutable
object array without ever having to call set on the TreeMap after
modification:

class Hidden<K, V> {
    TreeMap<K, Object[]> map = new TreeMap<>();

    V put(K k, V v) {
        if (map.isEmpty()) {
            map.put(k, new Object[] {v});
            return null;
        }
        Entry<K, Object[]> e = map.ceilingEntry(k);
        Object[] o = e.getValue();
        // ugly
        @SuppressWarnings("unchecked")
        V old = (V) o[0];
        o[0] = v;
        return old;
    }
}

This will be memory inefficient as each entry in the TreeMap has an
additional pointer.

Depending on what your API is then other methods requiring indirection will
also be inefficient. However you can provide methods to bulk search the
collection with minimal object allocation (forEach) or to do bulk changes
(replaceAll).

Alex

Reply via email to