php中自定义hashmap类

来源:互联网 发布:中国大萧条 知乎 编辑:程序博客网 时间:2024/05/02 04:31

<?php


/**
 * @(#)hashable.php
 * PHP version 5.2.3
 *
 *
 * Copyright 2007 SoftRoad. All Rights Reserved.
 *
 *====================================================================
 * 変更履歴
 *
 * 新規作成                            2007 年5月17日   蒋彪
 */

class HashTable {

 var $H_table;

 /*
  *   コンストラクタ
  */
 function __construct() {
  $this->H_table = array ();
 }

 /*
  Object put(key,value)
 */
 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;
  }
 }

 /*
  void clear()
 */
 function clear() {
  $this->H_table = null;
  $this->H_table = array ();
 }

 /*
  boolean containsValue(value)
 */
 function containsValue($value) {

  while ($curValue = current($this->H_table)) {
   if ($curValue == $value) {
    return true;
   }
   next($this->H_table);
  }

  return false;

 }

 /*
  boolean containsKey(key)
 */
 function containsKey($key) {
  if (array_key_exists($key, $this->H_table)) {
   return true;
  } else {
   return false;
  }
 }

 /*
  object get(key)
 */
 function get($key) {
  if (array_key_exists($key, $this->H_table))
   return $this->H_table[$key];
  else
   return null;
 }

 /*
  boolean isEmpty()
 */
 function isEmpty() {
  return (count($this->H_table) == 0);
 }

 /*
  *int size()
  */
 function size() {
  return count($this->H_table);
 }

 /*
  *対象を削除します
  */
 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;
 }

 function toString() {
  print_r($this->H_table);
 }
}
?>
 

原创粉丝点击