Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ArrayList implements ArrayAccess, IteratorAggregate, Countable {
- private $list = array();
- function add($value, $index=null) {
- $this->offsetSet($index, $value);
- }
- function addAll(array &$values) {
- foreach($values as &$value) {
- $this->add($value);
- }
- }
- function clear() {
- $this->list = array();
- }
- function contains($value) {
- return in_array($this->list);
- }
- function indexOf($value) {
- foreach($this->list as $index=>$sValue) {
- if($value===$sValue) {
- return $index;
- }
- }
- return -1;
- }
- function isEmpty() {
- return $this->count() == 0;
- }
- function count() {
- return count($this->list);
- }
- function get($index) {
- if (!is_numeric($offset) || $offset!=(int)$offset) {
- throw new InvalidArgumentException(
- "Index to ".get_class($this)." must be an integer."
- );
- }
- $this->offsetGet($index);
- }
- function remove($index) {
- $this->offsetUnset($index);
- }
- function set($index, $value) {
- $this->offsetSet($index, $value);
- }
- function size() {
- return $this->count();
- }
- function toArray() {
- return $this->list;
- }
- function offsetExists($offset) {
- if (!is_numeric($offset) || $offset!=(int)$offset) {
- throw new InvalidArgumentException(
- "Index to ".get_class($this)." must be an integer."
- );
- }
- return array_key_exists($offset, $this->list);
- }
- function offsetGet($offset) {
- if (!is_numeric($offset) || $offset!=(int)$offset) {
- throw new InvalidArgumentException(
- "Index to ".get_class($this)." must be an integer."
- );
- }
- if (offsetExists($offset))
- return $this->list[$offset];
- throw new OutOfBoundsException("Index '$offset' does not exist.");
- }
- function offsetSet($offset, $value) {
- if ($offset==null) {
- $this->list[] = $value;
- } else{
- if (!is_numeric($offset) || $offset!=(int)$offset) {
- throw new InvalidArgumentException(
- "Index to ".get_class($this)." must be an integer."
- );
- }
- if ($offset<0 || $offset>=$this->size())
- throw new OutOfBoundsException("Index '$offset' does not exist.");
- $this->list[$offset] = $value;
- }
- }
- function offsetUnset($offset) {
- if (!is_numeric($offset) || $offset!=(int)$offset) {
- throw new InvalidArgumentException(
- "Index to ".get_class($this)." must be an integer."
- );
- }
- unset($this->list[$offset]);
- $this->list = array_values($this->list);
- }
- function getIterator() {
- return new ArrayIterator($this->list);
- }
- }
- $list = new ArrayList();
- $list->add(1);
- try {
- $list[1] = 2;
- echo "'\$list[1] = 2' should have thrown an OutOfBoundsError(), did not");
- exit(1);
- } catch (OutOfBoundsException $error) {}
- $list[] = 2;
- if($list->get(1)!=2)
- echo "'\$list->get(1)' did not return '2', returned '{$list->get(1)}'";
- if($list->size()!=2)
- echo "'\$list->size()' did not return '2', returned '{$list->size()}'";
- ?>
Advertisement
Add Comment
Please, Sign In to add comment