/**
* 参考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;
}
}