js 实现java中hashMap

本文介绍了一种使用JavaScript实现的HashMap数据结构,该结构提供了完整的增删查改等基本操作,并实现了如size、isEmpty、containsKey等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 参考java中HashMap
 * 基本上实现Map接口
 * @author chitianxiang $Date: July 5, 2012 - Thursday - 11: 28 AM
 */
function HashMap(){
	this._table = {};
	this._size = 0;
		
	if (typeof HashMap._initialized == "undefined") {
		
		//返回 key-value 映射的数量
		HashMap.prototype.size = function() {
			return this._size;
		}
		
		//判断 map 是否为空
		HashMap.prototype.isEmpty = function() {
			return this._size > 0;
		}
		
		//是否包含 key
		HashMap.prototype.containsKey = function(key) {
			return (key in this._table);
		}
		
		//是否包含 value 
		HashMap.prototype.containsValue = function(value) {
			var flag = false;
			for (var key in this._table) {
				if (this._table[key] == value) {
					flag = true;
					break;
				}
			}
			return flag;
		}
		
		//取出key 对应的 value
		HashMap.prototype.get = function(key) {
			return (this.containsKey(key) ? this._table[key] : null);
		}
		
		//存入 key-value 映射
		HashMap.prototype.put = function(key, value) {
			if (!this.containsKey(key)) {
				this._size++;
			}
			this._table[key] = value;
		}
		
		//移除key 及其映射的 value
		HashMap.prototype.remove = function(key) {
			if (this.containsKey(key) && (delete this._table[key])) {
				this._size--;
			}
		}
		
		//将别的hashMap放入当前map中
		HashMap.prototype.putAll = function(hashMap) {
			try {
				if (hashMap.constructor.name == "HashMap") {
					for (var key in hashMap._table) {
						this.put(key, hashMap.get(key));
					}
				}
			} catch (e) {
				throw "HashMap.putAll(hashMap) errorCode< " + e + " >";	
			}
		}
		
		//清除Map
		HashMap.prototype.clear = function() {
			this._table = {};
			this._size = 0;
		}
		
		//返回所有 key 集合
		HashMap.prototype.keySet = function() {
			var keySet = [];
			for (var key in this._table) {
				keySet.push(key);
			}
			return keySet;
		}
		
		//返回所有 value 集合
		HashMap.prototype.values = function() {
			var values = [];
			for (var key in this._table) {
				values.push(this._table[key]);
			}
			return values;
		}
		
		HashMap._initialized = true;
	}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值