Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active February 25, 2021 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Crydust/7087e6a85369e4f8131cdb159767173e to your computer and use it in GitHub Desktop.
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
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