Package exercise2.exercise2_16

Source Code of exercise2.exercise2_16.LinkedList

package exercise2.exercise2_16;

import exercise2.exercise2_10.Vehicle;

/**
* LinkedList class which has a value and reference to the next in the list.
* @author kubotamochi
*
*/
public class LinkedList {

  /** the value of this object */
  private Object value;
  /** reference to the next object in the list */
  private LinkedList next;
 
  /** The constructor with object's value parameter */
  public LinkedList(Object value) {
    this.value = value;
  }
 
  /** The constructor with object's value and the next object parameters */
  public LinkedList(Object value, LinkedList next) {
    this(value);
    this.next = next;
  }
 
  @Override
  public String toString() {
    StringBuilder str = new StringBuilder();
    str.append(value.toString());
    str.append(" ");
    if(next != null) {
      str.append("before of ");
      str.append(next.toString());
    }
   
    return str.toString();
  }

  /**
   * Counts nodes of the List.
   * @return number of nodes.
   */
  public int countNode() {
    int cnt = 1;
    LinkedList node = next;
    while(node != null) {
      cnt++;
      node = node.next;
    }
   
    return cnt;
  }
 
  public Object getValue() {
    return value;
  }
  public LinkedList getNext() {
    return next;
  }
  public void setNext(LinkedList next) {
    this.next = next;
  }
 
  public static void main(String[] args) {
    final int VEHICLE_NUM = 5;
    final String OWNER = "Kubota";
    Vehicle[] vehicles = new Vehicle[VEHICLE_NUM];
   
    
    for(int i = 0; i < vehicles.length; i++) {
      vehicles[i] = new Vehicle();
      vehicles[i].setOwner(OWNER);
      vehicles[i].setSpeed(Math.random() * i);
      vehicles[i].setDirection(Math.random() * i);
    }
   
    LinkedList startNode = new LinkedList(vehicles[0]);
   
    LinkedList node = startNode;
    for(int i = 1; i < vehicles.length; i++) {
      node.setNext(new LinkedList(vehicles[i]));
      node = node.next;
    }
   
    node = startNode;
    while(node != null) {
      Vehicle output = (Vehicle)node.getValue();
      System.out.println("ID : " + output.getId());
      System.out.println("OWNER : " + output.getOwner());
      System.out.println("SPEED : " + output.getSpeed());
      System.out.println("DIRECTION : " + output.getDirection());
      System.out.println();
     
      node = node.next;
    }
   
    System.out.println(startNode.toString());
  }
}
TOP

Related Classes of exercise2.exercise2_16.LinkedList

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.