All Downloads are FREE. Search and download functionalities are using the official Maven repository.

no.motif.maps.FnAsMap Maven / Gradle / Ivy

The newest version!
package no.motif.maps;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import no.motif.f.Fn;


class FnAsMap implements Map {

    private final Fn fn;

    private final Map overrides;
    private final Map removed;

    FnAsMap(Fn fn) {
        this.fn = fn;
        this.overrides = new HashMap<>();
        this.removed = new HashMap<>();
    }


    @Override
    public boolean containsKey(Object key) {
        @SuppressWarnings("unchecked")
        K castedKey = (K) key;
        return !removed.containsKey(key) && (overrides.containsKey(key) || fn.$(castedKey) != null);
    }


    @Override
    public V get(Object key) {
        if (overrides.containsKey(key)) return overrides.get(key);
        if (removed.containsKey(key)) return null;
        @SuppressWarnings("unchecked")
        K castedKey = (K) key;
        return fn.$(castedKey);
    }

    @Override
    public V put(K key, V value) {
        V previous = get(key);
        removed.remove(key);
        overrides.put(key, value);
        return previous;
    }

    @Override
    public V remove(Object key) {
        V previous = get(key);
        removed.put(key, previous);
        overrides.remove(key);
        return previous;
    }

    @Override
    public void putAll(Map m) {
        for (Map.Entry entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public void clear() {
        overrides.clear();
        removed.clear();
    }

    @Override
    public int size() {
        throw new NotPossibleOnMapViewOfFn(fn, "the size cannot be determined"); }

    @Override
    public boolean isEmpty() {
        throw new NotPossibleOnMapViewOfFn(fn, "it cannot be determined if it is empty"); }

    @Override
    public boolean containsValue(Object v) {
        throw new NotPossibleOnMapViewOfFn(fn, "it cannot be determined if it contains the value '" + v + "'"); }

    @Override
    public Set keySet() {
        throw new NotPossibleOnMapViewOfFn(fn, "it is not possible derive a set of keys."); }

    @Override
    public Collection values() {
        throw new NotPossibleOnMapViewOfFn(fn, "it is not possible resolve the values."); }

    @Override
    public Set> entrySet() {
        throw new NotPossibleOnMapViewOfFn(fn, "it is not possible derive the entries."); }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy