More strongly enforced canonical mappings using PutOnceMap

Ever used a Map for a canonical mapping? But what if someone due to a bug, creates another instance when a canonical instance is already “canonized”?

This class ensures this potential bug to be fail-fast.

package com.karoldepka.librelib;

import java.util.HashMap;

 * A HashMap for canonical mapping which ensures fail-fast behavior if someone tries
 * to change the mapping of an already "canonized" key+value.
 * @author Karol Depka Pradzinski
 * @license LGPL
public class PutOnceMap<TKey, TValue> extends HashMap<TKey, TValue> {
	public TValue put(TKey key, TValue value) {
		TValue currentVal = get(key);
		if ( currentVal != null ) {
			if ( currentVal != value ) {
				throw new RuntimeException("Cannot change mapping for key " +key + " to value " +
						value + " from value " + get(key));
			} else {
				// unnecessary put
				return currentVal;
		} else {
			return super.put(key,value);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s