/*
 * Copyright 2006 Mask@ Project.
 * 
 * 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 org.maskat.framework;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class DefChildList extends ArrayList {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Iterator childItr(Class clazz) {
		return new Itr(clazz);
	}

	private class Itr implements Iterator {
		Itr(Class clazz) {
			this.clazz = clazz;
		}

		Class clazz;

		int cursor = 0;

		int lastRet = -1;

		int expectedModCount = modCount;

		public boolean hasNext() {
			// cursorからsize()間での間にclazzの要素があるか
			try {
				int temp = cursor;
				Object next = get(temp++);
				while (true) {
					if (clazz.isInstance(next)) {
						return true;
					}
					next = get(temp++);
				}
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				return false;
			}
		}

		public Object next() {
			checkForComodification();
			try {
				Object next = get(cursor);
				while (true) {
					if (clazz.isInstance(next)) {
						break;
					}
					cursor++;
					next = get(cursor);
				}
				lastRet = cursor++;
				return next;
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				throw new NoSuchElementException();
			}
		}

		public void remove() {
			throw new UnsupportedOperationException("remove is not supported");
		}

		final void checkForComodification() {
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();
		}
	}
}
