【Thinking in Java】Map通过关联数组的简单实现

参考: Thinking in Java

简介

Map的数据保存是以键值对的形式进行数据的保存,这种键值对的关联形式又叫映射表,或者说关联数组,那么如何用一个简单的数组来实现Map的基本形式.

代码

/**
 * @description 关系数组,又称为映射表
 * 这是Map实现的基本思想,即用键值对的形式保存数据
 * @author paul
 * @date 2017年6月14日 下午3:06:59 
 * @update 2017年6月14日 下午3:06:59 
 * @version V1.0
 */
public class AssociativeArray<K, V> {
	private Object[][] pairs;
	//关联数组的下标
	private int index;
	
	public AssociativeArray(int length) {
		pairs = new Object[length][2];
	}
	
	/**
	 * @param key
	 * @param value
	 * @description 放入元素
	 * @author paul
	 * @date 2017年6月14日 下午3:22:25
	 * @update 2017年6月14日 下午3:22:25
	 * @version V1.0
	 */
	public void put(K key, V value) {
		if (index >= pairs.length)
			throw new ArrayIndexOutOfBoundsException();
		pairs[index++] = new Object[]{key, value};
	}
	
	/**
	 * @param key
	 * @return
	 * @description 根据key值取出元素
	 * @author paul
	 * @date 2017年6月14日 下午3:22:33
	 * @update 2017年6月14日 下午3:22:33
	 * @version V1.0
	 */
	@SuppressWarnings("unchecked")
	public V get(K key) {
		//遍历关联数组,找到key相等的,返回value
		for (int i=0; i<pairs.length; i++)
			if (key.equals(pairs[i][0]))
				return (V)pairs[i][1];
		return null;//没有找到返回null
	}
	
	/**
	 * @param key
	 * @return
	 * @description 是否有某个主键
	 * @author paul
	 * @date 2017年6月16日 下午10:46:46
	 * @update 2017年6月16日 下午10:46:46
	 * @version V1.0
	 */
	public boolean contains(K key) {
		for (int i=0; i<pairs.length; i++)
			if (key.equals(pairs[i][0]))
				return true;
		return false;
	}
	
	/**
	 * @return
	 * @description 是否为空
	 * @author paul
	 * @date 2017年6月16日 下午10:48:15
	 * @update 2017年6月16日 下午10:48:15
	 * @version V1.0
	 */
	public boolean isEmpty() {
		return pairs.length == 0;
	}
	
	/**
	 * 
	 * @description 清空元素
	 * @author paul
	 * @date 2017年6月16日 上午9:00:47
	 * @update 2017年6月16日 上午9:00:47
	 * @version V1.0
	 */
	public void clear() {
		for (int i=0; i<pairs.length; i++) {
			pairs[i][0] = null;
			pairs[i][1] = null;
		}
	}
	
	//重写toString
	public String toString() {
		StringBuffer result = new StringBuffer("{");
		for (int i=0; i<index; i++) {
			result.append(pairs[i][0].toString());
			result.append(":");
			result.append(pairs[i][1].toString());
			if (i < index - 1) {
				result.append(",");
			} else {
				result.append("}");
			}
		}
		return result.toString();
	}
	
	public static void main(String[] args) {
		AssociativeArray<String, String> aa = new AssociativeArray<String, String>(2);
		aa.put("1", "语文");
		aa.put("2", "English");
		System.out.println(aa.index);
		System.out.println(aa.toString());
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值