/*
*@filename:    Map.js
*@content: 本程序用JS实现类拟JAVA中MAP类的功能
*/

//键值对对象
function Node(key, value)
{
	this.key = key;
	this.value = value;
}

//Map类
function Map()
{
	this.nodes = new Array();
}

//往容器中加入一个键值对
Map.prototype.put=function(key, value)
{
	for( var i = 0; i < this.nodes.length; i++ )
	{
		//如果键值已存在，则put方法为更新已有数据
		if( this.nodes[i].key == key )
		{
    	this.nodes[i].value = value;
    	return;
  	}		
	}

	var node=new Node(key,value);
	this.nodes.push(node);
	return;
}
   
//获取指定键的值
Map.prototype.get=function(key)
{
	for( var i = 0; i < this.nodes.length; i++ )
	{
		if( this.nodes[i].key == key )
			return this.nodes[i].value;
	}
  
 	return null;		
}

//取得索引指定的值
Map.prototype.getItemData=function(index)
{
	for( var i = 0; i < this.nodes.length; ++i)
	{
		if( i == index )
		{
			return this.nodes[i].value;
		}
	}	
	
	return null;
}
 
//获取容器中对象的个数    
Map.prototype.size=function()
{
	return this.nodes.length;
}

//清空容器        
Map.prototype.clear=function()
{
	while( this.nodes.length > 0 )
		this.nodes.pop();      
}
 
//删除指定值
Map.prototype.remove=function(key)
{
	for(var i = 0; i < this.nodes.length; i++)
	{
		if( this.nodes[i].key == key )
		{
   		var newarr = new Array();
        	 
    	if( i > 0 )
     	{
      	newarr = this.nodes.slice(0, i);
      	newarr = newarr.concat(this.nodes.slice(i+1)); 
      }
     	else//删除的是第一个元素
      {
        newarr = this.nodes.slice(1);
      }
           
      this.nodes=newarr;		
		}
	}
}

//是否为空   
Map.prototype.isEmpty=function()
{
	if( this.nodes.length == 0 )
  	return true;
	else
		return false;
}

//将map中的值连接以字符传方式返回
Map.prototype.toString=function()
{
	var str = "[";
  for( var i = 0; i < this.nodes.length; i++)
  {
    if( i < this.nodes.length-1 )
      str = str + this.nodes[i].key + ",";
    else
      str = str + this.nodes[i].key;    
  }
    
  str = str + "]";
  return str;
}