All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.cask.common.cli.internal.TreeNode Maven / Gradle / Ivy

There is a newer version: 0.11.0
Show newest version
/*
 * Copyright © 2012-2014 Cask Data, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package co.cask.common.cli.internal;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

/**
 * Represents a node in a tree.
 *
 * @param  type of object that the tree contains
 */
public class TreeNode {

  private final T data;
  private final ArrayList> children;
  private final TreeNode parent;

  public TreeNode(T data, TreeNode parent) {
    this.data = data;
    this.parent = parent;
    this.children = Lists.newArrayList();
  }

  public TreeNode() {
    this(null, null);
  }

  /**
   * Finds a child node.
   *
   * @param childData the child to find
   * @return the child node with the data that equals childData
   */
  public TreeNode findChild(T childData) {
    for (TreeNode candidate : children) {
      if (childData.equals(candidate.data)) {
        return candidate;
      }
    }
    return null;
  }

  /**
   * Finds a child node, and if it doesn't exist yet, create it before returning.
   * @param childData the child to find
   * @return the child node with the data that equals childData
   */
  public TreeNode findOrCreateChild(T childData) {
    for (TreeNode candidate : children) {
      if (childData.equals(candidate.data)) {
        return candidate;
      }
    }
    return addChild(childData);
  }

  public TreeNode addChild(T data) {
    TreeNode result = new TreeNode(data, this);
    children.add(result);
    return result;
  }

  public T getData() {
    return data;
  }

  public TreeNode getParent() {
    return parent;
  }

  public List> getChildren() {
    return children;
  }

  @Override
  public String toString() {
    return "TreeNode{" + data + '}';
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy