Last active
February 25, 2021 09:58
-
-
Save Crydust/7087e6a85369e4f8131cdb159767173e to your computer and use it in GitHub Desktop.
a logging map which can replace a HashMap and will log when it is being accessed or altered
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.util.stream.Collectors.toUnmodifiableSet; | |
import java.io.Serializable; | |
import java.util.AbstractMap; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
import java.util.Set; | |
import javax.annotation.Nonnull; | |
@SuppressWarnings("serial") | |
public final class LoggingMap<K, V> extends AbstractMap<K, V> implements Serializable { | |
private final String name; | |
private final LinkedHashMap<K, V> inner; | |
public LoggingMap(String name) { | |
this.name = name; | |
this.inner = new LinkedHashMap<>(); | |
} | |
public LoggingMap(String name, Map<K, V> map) { | |
this.name = name; | |
this.inner = new LinkedHashMap<>(map); | |
} | |
@Nonnull | |
@Override | |
public Set<Entry<K, V>> entrySet() { | |
System.out.println("*** " + name + ".entrySet"); | |
return inner.entrySet().stream() | |
.map(UnmodifiableEntry::new) | |
.collect(toUnmodifiableSet()); | |
} | |
@Override | |
public V put(K key, V value) { | |
System.out.println("*** " + name + ".put key = " + key + ", value = " + value); | |
return inner.put(key, value); | |
} | |
@Override | |
public V remove(Object key) { | |
System.out.println("*** " + name + ".remove key = " + key); | |
return inner.remove(key); | |
} | |
@Override | |
public void clear() { | |
System.out.println("*** " + name + ".clear"); | |
inner.clear(); | |
} | |
private static final class UnmodifiableEntry<K, V> implements Entry<K, V> { | |
private final K key; | |
private final V value; | |
public UnmodifiableEntry(Entry<K, V> entry) { | |
this(entry.getKey(), entry.getValue()); | |
} | |
public UnmodifiableEntry(K key, V value) { | |
this.key = key; | |
this.value = value; | |
} | |
@Override | |
public K getKey() { | |
return key; | |
} | |
@Override | |
public V getValue() { | |
return value; | |
} | |
@Override | |
public V setValue(V value) { | |
throw new UnsupportedOperationException("this entry is unmodifiable"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment