/** * Returns the lowest shared parent of the other state or null if these states have no common * parent. */ public State getLeastCommonParent(State other) { State least = null; State[] otherHierarchy = other.getHierarchy(); for (int i = 0; i < hierarchy.length; i++) { if (otherHierarchy.length <= i) break; else if (hierarchy[i] == other.getHierarchy()[i]) least = hierarchy[i]; else break; } return least; }
/** * Creates a new state. * * @param name A name that is unique within any state machine that contains this state * @param type A state type as defined by {@link StateType} * @param parent A parent state that contains this state if any * @param entryAction An action to perform on entering the state * @param exitAction An action to perform on leaving the state */ public State(String name, StateType type, State parent, Action entryAction, Action exitAction) { this.name = name; this.type = type; this.parent = parent; this.entryAction = entryAction; this.exitAction = exitAction; // Compute name and enclosing state hierarchy. if (parent == null) { this.qualifiedName = name; this.hierarchy = new State[] {this}; } else { this.qualifiedName = parent.getName() + ":" + name; State[] parentArray = parent.getHierarchy(); State[] selfArray = new State[parentArray.length + 1]; for (int i = 0; i < parentArray.length; i++) selfArray[i] = parentArray[i]; selfArray[selfArray.length - 1] = this; this.hierarchy = selfArray; } if (parent == null) {} }
/** Returns true if the other state encloses this one. */ public boolean isSubstateOf(State other) { if (parent == null) return false; else if (parent == other) return true; else return parent.isSubstateOf(other); }