private List<Segment> parse(String template) { List<Segment> ret = new ArrayList<Segment>(); int idx = 0; SegmentAndState currentState = new SegmentAndState(); currentState.state = ParserState.START; while(idx < template.length()) { char c = template.charAt(idx); Segment lastSegment = currentState.segment; currentState = currentState.state.process(currentState, c); //if the state created a new segment, store it in the results and //continue with it. yes, the reference equality is what we want here if (lastSegment != currentState.segment) { ret.add(currentState.segment); } ++idx; } currentState.state.process(currentState, null); return ret; }