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

cn.hutool.core.map.TolerantMap Maven / Gradle / Ivy

The newest version!
package cn.hutool.core.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 一个可以提供默认值的Map
 *
 * @param  键类型
 * @param  值类型
 * @author pantao, looly
 */
public class TolerantMap extends MapWrapper {
	private static final long serialVersionUID = -4158133823263496197L;

	private final V defaultValue;

	/**
	 * 构造
	 *
	 * @param defaultValue 默认值
	 */
	public TolerantMap(V defaultValue) {
		this(new HashMap<>(), defaultValue);
	}

	/**
	 * 构造
	 *
	 * @param initialCapacity 初始容量
	 * @param loadFactor      增长因子
	 * @param defaultValue    默认值
	 */
	public TolerantMap(int initialCapacity, float loadFactor, V defaultValue) {
		this(new HashMap<>(initialCapacity, loadFactor), defaultValue);
	}

	/**
	 * 构造
	 *
	 * @param initialCapacity 初始容量
	 * @param defaultValue    默认值
	 */
	public TolerantMap(int initialCapacity, V defaultValue) {
		this(new HashMap<>(initialCapacity), defaultValue);
	}

	/**
	 * 构造
	 *
	 * @param map          Map实现
	 * @param defaultValue 默认值
	 */
	public TolerantMap(Map map, V defaultValue) {
		super(map);
		this.defaultValue = defaultValue;
	}

	/**
	 * 构建TolerantMap
	 *
	 * @param map          map实现
	 * @param defaultValue 默认值
	 * @param           键类型
	 * @param           值类型
	 * @return TolerantMap
	 */
	public static  TolerantMap of(Map map, V defaultValue) {
		return new TolerantMap<>(map, defaultValue);
	}

	@Override
	public V get(Object key) {
		return getOrDefault(key, defaultValue);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		if (false == super.equals(o)) {
			return false;
		}
		final TolerantMap that = (TolerantMap) o;
		return getRaw().equals(that.getRaw())
				&& Objects.equals(defaultValue, that.defaultValue);
	}

	@Override
	public int hashCode() {
		return Objects.hash(getRaw(), defaultValue);
	}

	@Override
	public String toString() {
		return "TolerantMap{" + "map=" + getRaw() + ", defaultValue=" + defaultValue + '}';
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy