PHP实现HashMap

这篇博客介绍了如何用PHP实现HashMap数据结构,包括构造函数、添加键值对、根据key获取value、删除键值对、获取所有键和值、将一个HashMap的值放入当前HashMap、移除所有元素、检查值是否存在、检查键是否存在、获取元素个数以及判断HashMap是否为空等操作。示例代码详细展示了每个方法的实现细节。

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

Class HashMap{
 var $H_table;

  /*
   * HashMap构造函数
   */
  public function __construct() {
   $this->H_table = array ();
  }

  /*
   *向HashMap中添加一个键值对
   *@param $key 插入的键
   *@param $value 插入的值
  */
 public function put($key, $value) {
  if (!array_key_exists($key, $this->H_table)) {
     $this->H_table[$key] = $value;
     return null;
  } else {
     $tempValue = $this->H_table[$key];
     $this->H_table[$key] = $value;
     return $tempValue;
  }
  }
 
  /*
  * 根据key获取对应的value
  * @param $key
  */
  public function get($key) {
   if (array_key_exists($key, $this->H_table))
    return $this->H_table[$key];
   else
    return null;
  }

  /*
   *移除HashMap中所有键值对
  */
  /*
   *删除指定key的键值对
   *@param $key 要移除键值对的key
   */
  public function remove($key) {
   $temp_table = array ();
   if (array_key_exists($key, $this->H_table)) {
    $tempValue = $this->H_table[$key];
    while ($curValue = current($this->H_table)) {
     if (!(key($this->H_table) == $key))
      $temp_table[key($this->H_table)] = $curValue;
 
     next($this->H_table);
    }
    $this->H_table = null;
    $this->H_table = $temp_table;
    return $tempValue;
   } else
    return null;
  }
 
  /**
   * 获取HashMap的所有键值
   * @return 返回HashMap中key的集合,以数组形式返回
   */
  public function keys(){
   return array_keys($this->H_table);
  }
  /**
   * 获取HashMap的所有value值
   */
  public function values(){
   return array_values($this->H_table);
  }
 
  /**
   * 将一个HashMap的值全部put到当前HashMap中
   * @param $map
   */
  public function putAll($map){
   if(!$map->isEmpty()&& $map->size()>0){
    $keys = $map->keys();
    foreach($keys as $key){
     $this->put($key,$map->get($key));
    }
   }
  }
 
  /**
   * 移除HashMap中所有元素
   */
  public function removeAll() {
   $this->H_table = null;
   $this->H_table = array ();
  }

  /*
   *HashMap中是否包含指定的值
   *@param $value
  */
  public function containsValue($value) {
    while ($curValue = current($this->H_table)) {
     if ($curValue == $value) {
      return true;
     }
     next($this->H_table);
    }
    return false;
  }

  /*
   *HashMap中是否包含指定的键key
   *@param $key
  */
  public function containsKey($key) {
    if (array_key_exists($key, $this->H_table)) {
     return true;
    } else {
     return false;
    }
  }

  /*
   *获取HashMap中元素个数
   */
  public function size() {
   return count($this->H_table);
  }
 
 
  /*
  *判断HashMap是否为空
  */
  public function isEmpty() {
   return (count($this->H_table) == 0);
  }

  /**
   *
   */
  public function toString() {
   print_r($this->H_table);
  }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值