Dec 202012
 

Abstract class for the RList Interface in PHP

 

include_once("rc/collections/RList.php");

/**
 * RAbstractList implements composite methods for the RList interface.
 *
 * @author Steven Bolin - December 2012 - All rights reserved.
 */
abstract class RAbstractList implements RList {

  /**
   * Returns true if this list contains no elements, false otherwise.
   * @return boolean - Returns true if this list contains no elements, false otherwise.
   */
  public function isEmpty() {
    return $this->size() === 0;
  }

   /**
   * Appends the specified element to the end of this list.
   * @param mixed $element - The element to add to the List
   */
  public function add($element) {
   $this->addAt($this->size(), $element); 
  }

  /**
   * Returns true if this list contains the specified element, false otherwise.
   * @require - $content != null
   * @param mixed $element - The element to search for.
   * @return boolean - Returns true if this list contains the specified element, false otherwise.
   */
  public function contains($element) {
    $found = false;
    for($i=0; $i<$this->size() && !$found; $i++) {
      if($this->get($i) === $element) {
        $found = true;
      }
    }
    return $found;
  }

  /**
   * Returns the index of the first occurrence of the specified element in this 
   * list, or null if this list does not contain the element.
   * @param mixed $element - The element to get the index of.
   * @return int - Returns the index of the first occurrence of the specified 
   * element in this list, or null if this list does not contain the element.
   */
  public function indexOf($element) {
    $found = false;
    for($i=0; $i<$this->size() && !$found; $i++) {
      if($this->get($i) === $element) {
        $found = true;
      }
    }
    $i=$found?$i-1:null;
    return $i;
  }

  /**
   * Removes the first occurrence of the specified element from this list, if 
   * it is present
   * @param mixed $element - The element to remove the first occurance of.
   */
  public function remove($element) {
    $indexToRemove = $this->indexOf($element);
    if($indexToRemove !== null) {
      $this->removeIndex($indexToRemove);
    }
  }

  /**
   * Returns an array containing all of the elements in this list in proper 
   * sequence (from first to last element).
   * @return mixed array - Returns an array containing all of the elements in 
   * this list in proper sequence (from first to last element).
   */
  public function toArray() {
    $result = array();
    for($i=0; $i < $this->size(); $i++) {
      $result[$i] = $this->get($i);
    }
    return $result;
  }
} // end of class
 Posted by at 9:09 am