Economical.java

package org.microspace.util;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;

/**
 * Economical methods to prevent memory pile-up.
 * 
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2017-07-29
 */
public class Economical {
	public static <T> Set<T> unmodifiableSet (Set<T> set) {
		if (set == null) return null;
		Set<T> ret = Collections.unmodifiableSet(set);
		if (ret.getClass().isInstance(set)) {
			return set;
		}
		return ret; 
	}
	public static <T> SortedSet<T> unmodifiableSortedSet (SortedSet<T> set) {
		if (set == null) return null;
		SortedSet<T> ret = Collections.unmodifiableSortedSet(set);
		if (ret.getClass().isInstance(set)) {
			return set;
		}
		return ret; 
	}
	public static <K,V> Map<K,V> unmodifiableMap (Map<K,V> map) {
		if (map == null) return null;
		Map<K,V> ret = Collections.unmodifiableMap(map);
		if (ret.getClass().isInstance(map)) {
			return map;
		}
		return ret; 
	}
	public static <K,V> SortedMap<K,V> unmodifiableSortedMap (SortedMap<K,V> map) {
		if (map == null) return null;
		SortedMap<K,V> ret = Collections.unmodifiableSortedMap(map);
		if (ret.getClass().isInstance(map)) {
			return map;
		}
		return ret; 
	}
	public static <T> List<T> unmodifiableList (List<T> list) {
		if (list == null) return null;
		List<T> ret = Collections.unmodifiableList(list);
		if (ret.getClass().isInstance(list)) {
			return list;
		}
		return ret; 
	}
	public static <T> Collection<T> unmodifiableCollection (Collection<T> collection) {
		if (collection == null) return null;
		Collection<T> ret = Collections.unmodifiableCollection(collection);
		if (ret.getClass().isInstance(collection)) {
			return collection;
		}
		return ret; 
	}

}