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

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

There is a newer version: 5.8.27
Show newest version
package cn.hutool.core.map;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;

/**
 * 无重复键的Map
 * @author looly
 *
 * @param 
 * @param 
 */
public class TableMap implements Map, Serializable {
	private static final long serialVersionUID = -5852304468076152385L;

	private List keys;
	private List values;

	/**
	 * 构造
	 * 
	 * @param size 初始容量
	 */
	public TableMap(int size) {
		this.keys = new ArrayList<>(size);
		this.values = new ArrayList<>(size);
	}
	
	/**
	 * 构造
	 * 
	 * @param keys 键列表
	 * @param values 值列表
	 */
	public TableMap(K[] keys, V[] values) {
		this.keys = CollUtil.toList(keys);
		this.values = CollUtil.toList(values);
	}

	@Override
	public int size() {
		return keys.size();
	}

	@Override
	public boolean isEmpty() {
		return ArrayUtil.isEmpty(keys);
	}

	@Override
	public boolean containsKey(Object key) {
		return keys.contains(key);
	}

	@Override
	public boolean containsValue(Object value) {
		return values.contains(value);
	}

	@Override
	public V get(Object key) {
		final int index = keys.indexOf(key);
		if (index > -1 && index < values.size()) {
			return values.get(index);
		}
		return null;
	}

	@Override
	public V put(K key, V value) {
		keys.add(key);
		values.add(value);
		return null;
	}

	@Override
	public V remove(Object key) {
		int index = keys.indexOf(key);
		if (index > -1) {
			keys.remove(index);
			if (index < values.size()) {
				values.remove(index);
			}
		}
		return null;
	}

	@Override
	public void putAll(Map m) {
		for (Map.Entry entry : m.entrySet()) {
			this.put(entry.getKey(), entry.getValue());
		}
	}

	@Override
	public void clear() {
		keys.clear();
		values.clear();
	}

	@Override
	public Set keySet() {
		return new HashSet<>(keys);
	}

	@Override
	public Collection values() {
		return new HashSet<>(values);
	}

	@Override
	public Set> entrySet() {
		HashSet> hashSet = new HashSet<>();
		for(int i = 0; i < size(); i++) {
			hashSet.add(new Entry(keys.get(i), values.get(i)));
		}
		return hashSet;
	}

	private static class Entry implements Map.Entry{
		
		private K key;
		private V value;
		
		public Entry(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("setValue not supported.");
		}
		
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy