<?php
/*
Requires PHP Version >= 5
Original Author: Bryan Chen (me at bryanchen dot com) (http://www.bryanchen.com)
*/
include_once("class.ArrayList.php");
/*
Test class to demonstrate sorting.
To sort in ArrayList, following are required:
1. ArrayList must be typed
2. Type class must implement a public, static function called 'compare' that accepts 2 objects (type checking should be performed)
and returns a negative, positive or 0 value depending on whether obj1 is smaller than, greater than, or equals to obj2.
*/
class TestA {
private $value = 0;
public function __construct($integer = 0) {
$this->value = $integer;
}
public function getValue() {
return $this->value;
}
public static function compare($obj1, $obj2) {
return $obj1->getValue() - $obj2->getValue();
}
}
/***************************************/
// FOR TYPED ARRAYLISTS
/***************************************/
/* Creating and adding items to the ArrayList */
$typedList = new ArrayList("TestA");
$typedList->add(new TestA(100));
$typedList->add(new TestA(1));
$typedList->add(new TestA(10));
// NOTE: ArrayList will throw an Exception if type of item added is not of the specified type during instantiation.
/* Iterating through the ArrayList and sorting a typed ArrayList */
echo "\r\nBefore sorting...";
for ($i = 0; $i < $typedList->size(); $i++)
echo "\r\n$i: " . $typedList->get($i)->getValue();
echo "\r\nAfter sorting...";
// Sorting is typically achieved by calling sort() on the ArrayList.
// If no argument is specified, ArrayList will use a public static function called 'compare' that should exist on the typed class (i.e. TestA) to compare objects for sorting.
// If you like, you may specify an argument, which is the function's name (e.g. anotherCompareFunction, or something else)
$typedList->sort();
for ($i = 0; $i < $typedList->size(); $i++)
echo "\r\n$i: " . $typedList->get($i)->getValue();
/***************************************/
// FOR NON-TYPED ARRAYLISTS
/***************************************/
/* Creating and adding items to the ArrayList */
$list = new ArrayList();
$list->add("Item 1");
$list->add("Item 2");
$list->add("Item 3");
/* Removing an item */
$list->remove(0);
/* Replacing an item */
$list->set(0, "New Item 1");
$list->set(1, "New Item 2");
/* Getting size and testing for emptiness */
echo "\r\nIs empty: " . $list->isEmpty();
echo "\r\nArrayList size: " . $list->size();
/* Iterating through the ArrayList */
for ($i = 0; $i < $list->size(); $i++) {
echo "\r\nOUT: " . $list->get($i);
}
/* Get array of items from ArrayList */
$my_array = $list->toArray();
echo "\r\nArray size: " . sizeof($my_array);
/* Clear ArrayList of all items */
$list->clear();
echo "\r\nArrayList size after clear: " . $list->size();
?>
|