php 实现hashset
实现 HashSet 的基本思路
在 PHP 中,可以通过数组或 SplObjectStorage 类实现类似 HashSet 的功能。由于 PHP 数组的键具有唯一性,可以利用这一特性模拟 HashSet 的行为。

使用数组实现 HashSet
PHP 数组的键是唯一的,因此可以通过将值作为数组的键来实现 HashSet 的功能。以下是示例代码:
class HashSet {
private $elements = [];
public function add($value) {
$this->elements[$value] = true;
}
public function remove($value) {
unset($this->elements[$value]);
}
public function contains($value) {
return isset($this->elements[$value]);
}
public function size() {
return count($this->elements);
}
public function isEmpty() {
return $this->size() === 0;
}
public function clear() {
$this->elements = [];
}
public function values() {
return array_keys($this->elements);
}
}
使用 SplObjectStorage 实现 HashSet
如果需要存储对象,可以使用 SplObjectStorage 类,它专门用于存储对象并确保唯一性:
class ObjectHashSet {
private $storage;
public function __construct() {
$this->storage = new SplObjectStorage();
}
public function add($object) {
$this->storage->attach($object);
}
public function remove($object) {
$this->storage->detach($object);
}
public function contains($object) {
return $this->storage->contains($object);
}
public function size() {
return $this->storage->count();
}
public function isEmpty() {
return $this->size() === 0;
}
public function clear() {
$this->storage = new SplObjectStorage();
}
public function values() {
$values = [];
foreach ($this->storage as $object) {
$values[] = $object;
}
return $values;
}
}
注意事项
- 数组实现的 HashSet 适用于基本数据类型(如字符串、整数),但不能直接存储对象。
SplObjectStorage适用于存储对象,但不适用于基本数据类型。- 如果需要存储复杂数据类型(如关联数组),可以将其序列化为字符串后作为键存储。
示例用法
$hashSet = new HashSet();
$hashSet->add("apple");
$hashSet->add("banana");
echo $hashSet->contains("apple"); // 输出 1 (true)
echo $hashSet->size(); // 输出 2
$hashSet->remove("apple");
echo $hashSet->contains("apple"); // 输出空 (false)







