public interface IterateVisitor<T> extends Visitor2<T, Object, IterationInfo, Boolean> {
	
	/**
	 * visit for Boolean result
	 * @param t the element 
	 * @param param the extra parameter
	 * @param info the IterationInfo of current iterate
	 * @return the Boolean result of this visit
	 */
	Boolean visit(T t, Object param, IterationInfo info);
} public interface PredicateVisitor<T> extends ResultVisitor<T, Boolean> {

    /**
     * called when we want to predicate the item/pair with the param.
     *
     * @param t     the item
     * @param param the other param
     * @return true if predicate ok.
     */
    Boolean visit(T t, Object param);
} public interface ResultVisitor<T, Result> extends Visitor1<T, Object, Result> {

	/**
	 * called when visit the target element.
	 *
	 * @param t
	 *            the object
	 * @param param
	 *            the param data to carry when visit
	 * @return the visit result. or null if it is ignored.
	 */
	Result visit(T t, Object param);
	
} public static abstract class Callback{
		
	/**
	 * called on start iterate control.
	 * @param orderOps the order ops(operation),never null
	 * @param interceptOps  the intercept ops(operation),never null
	 */
	public void onStart(List<Integer> orderOps, List<Integer> interceptOps){
		// by default only delete and fiter op will intercept iteration.
		// that means if success the iterator will skip and continue next
		// iteration.
		interceptOps.add(OP_DELETE);
		interceptOps.add(OP_FILTER);

		/**
		 * default order is delete -> filter -> update -> insert
		 */
		orderOps.add(OP_DELETE);
		orderOps.add(OP_FILTER);
		orderOps.add(OP_UPDATE);
		orderOps.add(OP_INSERT);
	}
		
	/**
	 * apply the cache cmd for {@linkplain IterateControl}.
	 * this is only called by {@linkplain IterateControl#cache()}.
	 * Default is empty implements.
	 * @since 1.1.2
	 */
	public void applyCache() {
			
	}

	/**
	 * apply no cache
	 * @since 1.1.8
	 */
	public void applyNoCache() {

	}

	/**
	 * check the target operate
	 * @param op {@linkplain Operation#OP_DELETE} and etc.
	 */
	public void checkOperation(int op) {
			
	}

	/**
	 * save state of all ops
     * @param orderOps the order ops(opertion)
	 * @param interceptOps  the intercept ops(opertion)
	 */
	public abstract void saveState(List<Integer> orderOps, List<Integer> interceptOps);

} public final class InternalUtil {

	public static void checkCast(Class<?> parent, Class<?> child){
		if(!parent.isAssignableFrom(child)){
			throw new ClassCastException("type '"+ child.getName() + "' can't cast to '"
					+ parent.getName() + "'");
		}
	}

	public static void processThrowable(Throwable e, ThrowableVisitor tv) throws VisitException {
		if (tv != null) {
			tv.visit(e);
		} else {
			throw new VisitException(e);
		}
	}

	/**
	 * get the right {@linkplain CollectionVisitService}. often called by
	 * {@linkplain MapVisitService}.
	 * 
	 * @param <T>
	 *            the element type
	 * @param list
	 *            the list data
	 * @param c
	 *            the sort Comparator, can be null.
	 * @param sort
	 *            represent should regard as sorted
	 *            {@linkplain CollectionVisitService}. if false
	 *            {@linkplain #getVisitService(List, Comparator)} will be called
	 *            or else sort and return {@linkplain VisitServices#from(List)}
	 * @return an instance of {@linkplain CollectionVisitService}.
	 */
	public static <T> CollectionVisitService<T> getVisitService(List<T> list, Comparator<? super T> c, boolean sort) {
		// if should not sort return default CollectionVisitService .
		if (!sort) {
			return getVisitService(list, c);
		} else {
			if (c != null) {
				Collections.sort(list, c);
			}
			return VisitServices.from(list);
		}
	}

	/**
	 * get the collection visit service.
	 * @param <T>
	 *            the element type.
	 * @param c
	 *            sort comparator , can be null.
	 * @param list
	 *            the collection
	 * @return CollectionVisitService
	 */
	public static <T> CollectionVisitService<T> getVisitService(List<T> list, Comparator<? super T> c) {
		if (c != null) {
			Collections.sort(list, c);
		}
		return VisitServices.from(list);
	}

	/**
	 * create a map instance.
	 * 
	 * @param <K>
	 *            the key type.
	 * @param <V>
	 *            the value type.
	 * @param comparator
	 *            the key comparator , can be null.
	 * @return TreeMap or HashMap determined by target comparator.
	 */
	public static <K, V> Map<K, V> newMap(Comparator<? super K> comparator) {
		return comparator != null ? new TreeMap<K, V>(comparator) : new HashMap<K, V>();
	}

	/**
	 * auto Adaptation List, NavigableSet, SortedSet, Set and Collection.
	 * 
	 * @param <T>
	 *            the element type
	 * @param collection
	 *            the target collection
	 * @return a unmodifiable collection
	 */
	public static <T> Collection<T> unmodifiable(Collection<T> collection) {

		if (collection instanceof List) {
			return Collections.unmodifiableList((List<? extends T>) collection);
		}
		/*
		 * else if (collection instanceof NavigableSet) {
		 * if(JDKVersion.isJdK18()){ //jdk1.8 return
		 * Collections.unmodifiableNavigableSet((NavigableSet<T>) collection); }
		 * }
		 */
		else if (collection instanceof SortedSet) {
			return Collections.unmodifiableSortedSet((SortedSet<T>) collection);
		} else if (collection instanceof Set) {
			return Collections.unmodifiableSet((Set<? extends T>) collection);
		}
		return Collections.unmodifiableCollection(collection);
	}

	public static <K, V> Map<K, V> unmodifiable(Map<K, V> map) {
		// jdk1.8
		/*
		 * if (map instanceof NavigableMap) { return
		 * Collections.unmodifiableNavigableMap((NavigableMap<K, ? extends V>)
		 * map); } else
		 */
		if (map instanceof SortedMap) {
			return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
		}
		return Collections.unmodifiableMap(map);
	}

	public static String op2String(int op) {
		switch (op) {
		case OP_DELETE:
			return "OP_DELETE";

		case OP_FILTER:
			return "OP_FILTER";

		case OP_UPDATE:
			return "OP_UPDATE";

		case OP_INSERT:
			return "OP_INSERT";

		case OP_TRIM:
			return "OP_TRIM";
		default:
			return null;
		}
	}

} @SuppressWarnings("rawtypes")
public final class OperationPools {

    private static final int MAX_POOL_SIZE = 10;
    private static int sPOOL_SIZE_COP = 0;
    private static int sPOOL_SIZE_MOP = 0;

	private static final LinkedList<CollectionOperation> sPOOL_COLLECTION;
    private static final LinkedList<MapOperation> sPOOL_MAP;
    private static final Object sLOCK_COLLECTION;
    private static final Object sLOCK_MAP;

    static {
        sPOOL_COLLECTION = new LinkedList<CollectionOperation>();
        sPOOL_MAP = new LinkedList<MapOperation>();
        sLOCK_COLLECTION = new Object();
        sLOCK_MAP = new Object();
    }

    @SuppressWarnings("unchecked")
	public static <T> CollectionOperation<T> obtainCollectionOperation() {
        CollectionOperation co;
        synchronized (sLOCK_COLLECTION) {
            if ((co = sPOOL_COLLECTION.pollFirst()) != null) {
                sPOOL_SIZE_COP--;
            }
        }
        if (co == null) {
            return new CollectionOperation<T>() {
            };
        }
       // System.out.println("CollectionOperation: after obtainCollectionOperation(), pool size = " + sPOOL_SIZE_COP);
        return co;
    }

    public static void recycle(CollectionOperation cop) {
        if(cop != null) {
            cop.reset();
            synchronized (sLOCK_COLLECTION) {
                if (sPOOL_SIZE_COP < MAX_POOL_SIZE) {
                    sPOOL_COLLECTION.offerLast(cop);
                    sPOOL_SIZE_COP++;
                }
            }
          //  System.out.println("CollectionOperation: after recycle() pool size = " + sPOOL_SIZE_COP);
        }
    }

    public static void recycle(MapOperation mop) {
        if(mop != null) {
            mop.reset();
            synchronized (sLOCK_MAP) {
                if (sPOOL_SIZE_MOP < MAX_POOL_SIZE) {
                    sPOOL_MAP.offerLast(mop);
                    sPOOL_SIZE_MOP++;
                }
            }
          //  System.out.println("MapOperation: after recycle() pool size = " + sPOOL_SIZE_MOP);
        }
    }

    @SuppressWarnings("unchecked")
	public static <K, V> MapOperation<K, V> obtainMapOperation() {
        MapOperation mop;
        synchronized (sLOCK_MAP) {
            if ((mop = sPOOL_MAP.pollFirst()) != null) {
                sPOOL_SIZE_MOP --;
            }
        }
        if (mop == null) {
            return new MapOperation<K, V>() {
            };
        }
       // System.out.println("MapOperation: after obtainMapOperation() pool size = " + sPOOL_SIZE_MOP);
        return mop;
    }
    public static <T> void recycleAllCollectionOperation(List<CollectionOperation<T>> list){
    	//auto lock spread in jdk 1.6+
        for(CollectionOperation co : list){
            recycle(co);
        }
    }
    public static <K,V> void recycleAllMapOperation(List<MapOperation<K,V>> list){
        for(MapOperation co : list){
            recycle(co);
        }
    }

} public abstract class IterateState<T> {

	/**
	 * create and return a single iterate state
	 * 
	 * @param <T>
	 *            the type of collection
	 * @return an instance of IterateState
	 */
	public static <T> IterateState<T> singleIterateState() {
		return new SingleIterateState<T>();
	}

	/**
	 * create and return a multiple iterate state
	 * 
	 * @param <T>
	 *            the type of collection
	 * @return an instance of IterateState
	 */
	public static <T> IterateState<T> multipleIterateState() {
		return new MultipleIterateState<T>();
	}

	/**
	 * 
	 * execute the iteration of collection. contains the all operate in
	 * iteration.
	 * 
	 * @param collection
	 *            the collection to iterate
	 * @param hasExtra
	 *            whether has extra operate or not
	 * @param interceptor
	 *            the OperateInterceptor
	 * @param info
	 *            the iteration info of count. which will used from some
	 *            operate. such as insert,final insert.
	 * @param param
	 *            the param for iterate.
	 * @param predicate
	 *            the predicate visitor
	 * @param out
	 *            the out list , can be null if is single.
	 * @return the result which is match the predicate visitor, if it's single
	 *         state. or else return null.
	 */
	public T visit(Collection<T> collection, boolean hasExtra, CollectionOperateInterceptor<T> interceptor,
			IterationInfo info, Object param, PredicateVisitor<? super T> predicate, @Nullable List<T> out) {

		final Iterator<T> it = (collection instanceof List) ? ((List<T>) collection).listIterator()
				: collection.iterator();
		if (hasExtra) {
			interceptor.begin();
			T result = visitImpl(true, interceptor, param, predicate, it, info, out);
			interceptor.end();
			return result;
		}
		return visitImpl(false, interceptor, param, predicate, it, info, out);
	}

	/**
	 * 
	 * execute the iteration of collection. contains the all operate in
	 * iteration.
	 * 
	 * @param <R>
	 *            the result type of visit
	 * 
	 * @param collection
	 *            the collection to iterate
	 * @param hasExtra
	 *            whether has extra operate or not
	 * @param interceptor
	 *            the GroupOperateInterceptor
	 * @param info
	 *            the iteration info of count. which will used from some
	 *            operate. such as insert,final insert.
	 * @param param
	 *            the param for iterate.
	 * @param predicate
	 *            the predicate visitor
	 * @param resultVistor
	 *            the result visitor
	 * @param out
	 *            the out list , can be null if is single.
	 * @return the result which is match the predicate visitor, if it's single
	 *         state. or else return null.
	 */
	public <R> R visitForResult(Collection<T> collection, boolean hasExtra, CollectionOperateInterceptor<T> interceptor,
			IterationInfo info, Object param, PredicateVisitor<? super T> predicate,
			ResultVisitor<? super T, R> resultVistor, @Nullable List<R> out) {
		
		final Iterator<T> it = (collection instanceof List) ? ((List<T>) collection).listIterator()
				: collection.iterator();
		
		if (hasExtra) {
			interceptor.begin();
			R result = visitForResultImpl(true, interceptor, param, predicate,
					resultVistor, it, info, out);
			interceptor.end();
			return result;
		}
		return visitForResultImpl(false, interceptor, param, predicate,
				resultVistor, it, info, out);
	}

	/**
	 * visit the collection for result.
	 * 
	 * @param hasExtra
	 *            if has extra operation for current visit.
	 * @param interceptor
	 *            the operate interceptor
	 * @param param
	 *            the parameter
	 * @param predicate
	 *            the predicate visitor
	 * @param resultVistor
	 *            the result visitor
	 * @param it
	 *            the Iterator for collection
	 * @param info
	 *            the IterationInfo
	 * @param out
	 *            the out list. may be null if is {@link SingleIterateState}.
	 * @return the result , may be null if is {@link MultipleIterateState}}.
	 */
	protected abstract <R> R visitForResultImpl(boolean hasExtra, CollectionOperateInterceptor<T> interceptor,
			Object param, PredicateVisitor<? super T> predicate, ResultVisitor<? super T, R> resultVistor,
			Iterator<T> it, IterationInfo info, List<R> out);

	/**
	 * visit the collection
	 * 
	 * @param hasExtra
	 *            if has extra operation for current visit.
	 * @param groupInterceptor
	 *            the operate interceptor
	 * @param param
	 *            the parameter
	 * @param predicate
	 *            the predicate visitor
	 * @param it
	 *            the Iterator for collection
	 * @param info
	 *            the IterationInfo
	 * @param out
	 *            the out list. may be null if is {@link SingleIterateState}.
	 * @return the result , may be null if is {@link MultipleIterateState}}.
	 */
	protected abstract T visitImpl(boolean hasExtra, CollectionOperateInterceptor<T> groupInterceptor, Object param,
			PredicateVisitor<? super T> predicate, Iterator<T> it, IterationInfo info, List<T> out);
} public class Collections2 {
	
	/*
	 * update the all element if the result of ResultVisitor return not null. 
	 * @param <T> the element type
	 * @param <R> the result type
	 * @param src the collection
	 * @param param the extra parameter
	 * @param maxLeng the max length of update item count.
	 * @param visitor the result visitor.
	 * @param operator the operator
	 * @return true if update success(at least).
	 * @since 2.0.0
	 * @see ListIterator
     * @see Updatable
	 */
	//@SuppressWarnings("unchecked")
	/*public static <T,R> boolean updateAll(Collection<T> src, Object param, int maxLeng,
			ResultVisitor<? super T, T> visitor , Operator<T, R> operator) {
        Throwables.checkNull(src);
        Throwables.checkNull(visitor);
        
        boolean isList;
		Iterator<T> li;
		if(src instanceof List){
			isList = true;
			li = ((List<T>) src).listIterator();
		}else{
			isList = false;
			li = src.iterator();
		}
		// iterate
		T t = null;
		T result = null;
		int size = 0;
		for( ; li.hasNext();){
			t = li.next();
			operator.startVisitElement(t);
			result = visitor.visit(t, param);
			if(result != null){
				if(isList){
					((ListIterator<T>)li).set(result);
					if((size ++) > maxLeng){
						break;
					}
				}else if(t instanceof Updatable){
					((Updatable<T>) t).updateFrom(result);
					if((size ++) > maxLeng){
						break;
					}
				}
			}
		}
		return size > 0;
	}*/
	
	/*
	 * update the element which is assigned by target predicate visitor.
	 * @param <T> the element type
	 * @param <R> the result type
	 * @param src the src collection
	 * @param newT the new element
	 * @param param the param
	 * @param predicate the predicate visitor
	 * @param operator the operator
	 * @return true if update success.
	 * @since 2.0.0
	 * @see ListIterator
     * @see Updatable
	 */
	@SuppressWarnings("unchecked")
	/*public static <T,R> boolean update(Collection<T> src, T newT,
			Object param, PredicateVisitor<? super T> predicate, Operator<T, R> operator){
		boolean isList;
		Iterator<T> li;
		if(src instanceof List){
			isList = true;
			li = ((List<T>) src).listIterator();
		}else{
			isList = false;
			li = src.iterator();
		}
		// iterate
		T t = null;
		for( ; li.hasNext();){
			t = li.next();
			operator.startVisitElement(t);
			if(isTrue(predicate.visit(t, param))){
				//if list or element impl Updatable.
				if(isList){
					((ListIterator<T>)li).set(newT);
					return true;
				}
				if(t instanceof Updatable){
					((Updatable<T>) t).updateFrom(newT);
					return true;
				}
			}
		}
		return false;
	}
	*/
	public static <T> List<T> asList(Collection<T> coll){
		if(coll instanceof List){
			return (List<T>) coll;
		}
		throw new UnsupportedOperationException();
	}
	
	public static<T> SortedSet<T> asSortedSet(Collection<T> coll){
		if(coll instanceof SortedSet){
			return (SortedSet<T>) coll;
		}
		throw new UnsupportedOperationException();
	}
	
}
 public interface Observer<T, R> {

	/**
	 * called on operate success.
	 * @param param the extra parameter
	 * @param r the result when success.
	 */
	void onSuccess(Object param, R r);

	/**
	 * called on operate failed.
	 * @param param the parameter.
	 * @param t the element when failed.
	 */
	void onFailed(Object param, T t);

	/**
	 * called on throwable during visit operation.
	 * @param param the parameter.
	 * @param t the element when throwable during visit operation.
	 * @param e the throwable.
	 */
	void onThrowable(Object param, T t, Throwable e);

}
 public class SparseArray<E> {
    private static final Object DELETED = new Object();
    private boolean mGarbage = false;

    /**
     * Creates a new SparseArray containing no mappings.
     */
    public SparseArray() {
        this(10);
    }

    /**
     * Creates a new SparseArray containing no mappings that will not
     * require any additional memory allocation to store the specified
     * number of mappings.
     */
    public SparseArray(int initialCapacity) {
        mKeys = new int[initialCapacity];
        mValues = new Object[initialCapacity];
        mSize = 0;
    }

    /**
     * Gets the Object mapped from the specified key, or <code>null</code>
     * if no such mapping has been made.
     */
    public E get(int key) {
        return get(key, null);
    }

    /**
     * Gets the Object mapped from the specified key, or the specified Object
     * if no such mapping has been made.
     */
    @SuppressWarnings("unchecked")
	public E get(int key, E valueIfKeyNotFound) {
        int i = binarySearch(mKeys, 0, mSize, key);

        if (i < 0 || mValues[i] == DELETED) {
            return valueIfKeyNotFound;
        } else {
            return (E) mValues[i];
        }
    }

    /**
     * Removes the mapping from the specified key, if there was any.
     */
    public void delete(int key) {
        int i = binarySearch(mKeys, 0, mSize, key);

        if (i >= 0) {
            if (mValues[i] != DELETED) {
                mValues[i] = DELETED;
                mGarbage = true;
            }
        }
    }

    /**
     * Alias for {@link #delete(int)}.
     */
    public void remove(int key) {
        delete(key);
    }

    private void gc() {
        // Log.e("SparseArray", "gc start with " + mSize);

        int n = mSize;
        int o = 0;
        int[] keys = mKeys;
        Object[] values = mValues;

        for (int i = 0; i < n; i++) {
            Object val = values[i];

            if (val != DELETED) {
                if (i != o) {
                    keys[o] = keys[i];
                    values[o] = val;
                }

                o++;
            }
        }

        mGarbage = false;
        mSize = o;

        // Log.e("SparseArray", "gc end with " + mSize);
    }

    /**
     * Adds a mapping from the specified key to the specified value,
     * replacing the previous mapping from the specified key if there
     * was one.
     */
    public void put(int key, E value) {
        int i = binarySearch(mKeys, 0, mSize, key);

        if (i >= 0) {
            mValues[i] = value;
        } else {
            i = ~i;

            if (i < mSize && mValues[i] == DELETED) {
                mKeys[i] = key;
                mValues[i] = value;
                return;
            }

            if (mGarbage && mSize >= mKeys.length) {
                gc();

                // Search again because indices may have changed.
                i = ~binarySearch(mKeys, 0, mSize, key);
            }

            if (mSize >= mKeys.length) {
                int n = Math.max(mSize + 1, mKeys.length * 2);

                int[] nkeys = new int[n];
                Object[] nvalues = new Object[n];

                // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
                System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
                System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

                mKeys = nkeys;
                mValues = nvalues;
            }

            if (mSize - i != 0) {
                // Log.e("SparseArray", "move " + (mSize - i));
                System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
                System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
            }

            mKeys[i] = key;
            mValues[i] = value;
            mSize++;
        }
    }

    /**
     * Returns the number of key-value mappings that this SparseArray
     * currently stores.
     */
    public int size() {
        if (mGarbage) {
            gc();
        }

        return mSize;
    }

    /**
     * Given an index in the range <code>0...size()-1</code>, returns
     * the key from the <code>index</code>th key-value mapping that this
     * SparseArray stores.
     */
    public int keyAt(int index) {
        if (mGarbage) {
            gc();
        }

        return mKeys[index];
    }

    /**
     * Given an index in the range <code>0...size()-1</code>, returns
     * the value from the <code>index</code>th key-value mapping that this
     * SparseArray stores.
     */
    @SuppressWarnings("unchecked")
	public E valueAt(int index) {
        if (mGarbage) {
            gc();
        }

        return (E) mValues[index];
    }

    /**
     * Given an index in the range <code>0...size()-1</code>, sets a new
     * value for the <code>index</code>th key-value mapping that this
     * SparseArray stores.
     */
    public void setValueAt(int index, E value) {
        if (mGarbage) {
            gc();
        }

        mValues[index] = value;
    }

    /**
     * Returns the index for which {@link #keyAt} would return the
     * specified key, or a negative number if the specified
     * key is not mapped.
     */
    public int indexOfKey(int key) {
        if (mGarbage) {
            gc();
        }

        return binarySearch(mKeys, 0, mSize, key);
    }

    /**
     * Returns an index for which {@link #valueAt} would return the
     * specified key, or a negative number if no keys map to the
     * specified value.
     * Beware that this is a linear search, unlike lookups by key,
     * and that multiple keys can map to the same value and this will
     * find only one of them.
     */
    public int indexOfValue(E value) {
        if (mGarbage) {
            gc();
        }

        for (int i = 0; i < mSize; i++)
            if (mValues[i] == value)
                return i;

        return -1;
    }

    /**
     * Removes all key-value mappings from this SparseArray.
     */
    public void clear() {
        int n = mSize;
        Object[] values = mValues;

        for (int i = 0; i < n; i++) {
            values[i] = null;
        }

        mSize = 0;
        mGarbage = false;
    }

    /**
     * Puts a key/value pair into the array, optimizing for the case where
     * the key is greater than all existing keys in the array.
     */
    public void append(int key, E value) {
        if (mSize != 0 && key <= mKeys[mSize - 1]) {
            put(key, value);
            return;
        }

        if (mGarbage && mSize >= mKeys.length) {
            gc();
        }

        int pos = mSize;
        if (pos >= mKeys.length) {
            int n = Math.max(pos + 1, mKeys.length * 2);

            int[] nkeys = new int[n];
            Object[] nvalues = new Object[n];

            // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
            System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
            System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

            mKeys = nkeys;
            mValues = nvalues;
        }

        mKeys[pos] = key;
        mValues[pos] = value;
        mSize = pos + 1;
    }

    /**
     * Increases the size of the underlying storage if needed, to ensure that it can
     * hold the specified number of items without having to allocate additional memory
     * @param capacity the number of items
     */
    public void ensureCapacity(int capacity) {
        if (mGarbage && mSize >= mKeys.length) {
            gc();
        }

        if (mKeys.length < capacity) {
            int[] nkeys = new int[capacity];
            Object[] nvalues = new Object[capacity];

            System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
            System.arraycopy(mValues, 0, nvalues, 0, mValues.length);

            mKeys = nkeys;
            mValues = nvalues;
        }
    }

    private static int binarySearch(int[] a, int start, int len, int key) {
        int high = start + len, low = start - 1, guess;

        while (high - low > 1) {
            guess = (high + low) / 2;

            if (a[guess] < key)
                low = guess;
            else
                high = guess;
        }

        if (high == start + len)
            return ~(start + len);
        else if (a[high] == key)
            return high;
        else
            return ~high;
    }

    /**
     * @return a read-only list of the values in this SparseArray which are in ascending order, based on their
     * associated key
     */
    @SuppressWarnings("unchecked")
	public List<E> getValues() {
        return Collections.unmodifiableList(Arrays.asList((E[])mValues));
    }

    private int[] mKeys;
    private Object[] mValues;
    private int mSize;
} public final class Throwables {
	private Throwables(){}
	
	/**
	 * throw exception if fatal.
	 * @param e the throwable
	 * @since 1.1.7
	 */
	public static void throwIfFatal(Throwable e) {
		if (e instanceof Error) {
			throw (Error) e;
		} else if (e instanceof VisitException) {
			throw (VisitException) e;
		} else if (e instanceof RuntimeException) {
			throw (RuntimeException) e;
		} else {
			throw new RuntimeException(e);
		}
	}

	public static void checkNull(Object obj) {
		if (obj == null) {
			throw new NullPointerException();
		}
	}
	/**
	 * check the array if is empty.
	 * @param <T> the component tye of array.
	 * @param ts the array
	 * @since 2.0.0
	 */
	public static <T> void checkEmpty(T[] ts) {
		if (ts == null) {
			throw new NullPointerException();
		}
		if (ts.length == 0) {
			throw new IllegalArgumentException();
		}
	}

	public static <T> void checkEmpty(Collection<T> collection) {
		if (collection == null) {
			throw new NullPointerException();
		}
		if (collection.size() == 0) {
			throw new IllegalArgumentException();
		}
	}
	public static <K,V> void checkEmpty(Map<K,V> map) {
		if (map == null) {
			throw new NullPointerException();
		}
		if (map.size() == 0) {
			throw new IllegalArgumentException();
		}
	}
	public static <K,V> void checkEmpty(java.util.Map<K,V> map) {
		if (map == null) {
			throw new NullPointerException();
		}
		if (map.size() == 0) {
			throw new IllegalArgumentException();
		}
	}
} public abstract class Operation {

	/** indicate the operate of delete */
	public static final int OP_DELETE = 1;
	/** indicate the operate of filter, when iterate the element (nt collection ) or key-value pair 
	 * (in map) just skip it without do anything (if the visitor return true).  */
	public static final int OP_FILTER = 2;
	/** indicate the operate of update */
	public static final int OP_UPDATE = 3;
	/**
	 * indicate the operate of insert. Note this in only used for {@linkplain List}, or else
	 * have nothing effect.
	 */
	public static final int OP_INSERT = 4;
	
	/**
	 * indicate the operate of trim. only used for {@linkplain Map}}.
	 */
	public static final int OP_TRIM   = 5;

	/**
	 * the flag of 'if not exist'
	 * @since  1.1.6
	 */
	public static final int FLAG_CASE_IF_NOT_EXIST = 0x00000100;
	/**
	 * the flag of 'if exist'
	 * @since 1.1.6
	 */
	public static final int FLAG_CASE_IF_EXIST     = 0x00000200;
	private static final int MASK_OP               = 0x000000ff;
	private static final int MASK_FLAG             = 0xffffff00;

	/** you should not use member directly. use {@linkplain #setOperate(int)}, {@linkplain #getOperate()},
	 * {@linkplain #addFlags(int)} {@linkplain #deleteFlags(int)} instead.
	 * <h1>this will be private in v2.x .</h1>*/
	protected int mOp;
	/** the extra param for current operation. */
	protected Object mParam;
	
	
	protected Operation() {
		super();
	}
	
	public void reset(){
		mOp = 0;
		mParam = null;
	}
	/**
	 * set operate
	 * @param op the operate
	 * @since  1.1.6
	 */
	public void setOperate(int op){
		this.mOp = getFlags() + op;
	}
	/**
	 * get operate
	 * @return the operate
	 * @since  1.1.6
	 */
	public int getOperate(){
		return mOp & MASK_OP;
	}
	/**
	 * get flags
	 * @return the flags
	 * @since  1.1.6
	 */
	public int getFlags(){
		return mOp & MASK_FLAG;
	}
	/**
	 * add flags
	 * @param flags the flags
	 * @since  1.1.6
	 */
	public void addFlags(int flags){
		int ops = getOperate();
		mOp = (getFlags() | flags) + ops;
	}
	/**
	 * has flags
	 * @param flags the flags
	 * @since  1.1.6
	 */
	public boolean hasFlags(int flags){
		return (getFlags() & flags ) != 0;
	}

	/**
	 * delete flags
	 * @param flags the flags
	 * @since  1.1.6
	 */
	public void deleteFlags(int flags){
		int rawFlags = getFlags();
		rawFlags &=~flags;
		mOp = getOperate() + rawFlags;
	}
/*
	public static void main(String[] args){
		Operation ops = new Operation() {
			@Override
			public void reset() {
				super.reset();
			}
		};
		ops.mOp =2;
		ops.addFlags(FLAG_CASE_IF_NOT_EXIST);

		System.out.println(ops.hasFlags(FLAG_CASE_IF_NOT_EXIST));
		System.out.println(ops.getFlags()==FLAG_CASE_IF_NOT_EXIST);
		System.out.println(ops.getOperate()==2);
		ops.setOperate(3);
		System.out.println(ops.getOperate()==2);
		System.out.println(ops.getOperate()==3);
		ops.deleteFlags(FLAG_CASE_IF_NOT_EXIST);
		System.out.println(ops.hasFlags(FLAG_CASE_IF_NOT_EXIST));
	}*/
	
} public static boolean isTrue(Boolean value) {
	return value != null && value;
} public static <T> void checkEmpty(T[] ts) {
	if (ts == null) {
		throw new NullPointerException();
	}
	if (ts.length == 0) {
		throw new IllegalArgumentException();
	}
} public static void checkNull(Object obj) {
	if (obj == null) {
		throw new NullPointerException();
	}
}
import com.heaven7.java.visitor.IterateVisitor;
import com.heaven7.java.visitor.PredicateVisitor;
import com.heaven7.java.visitor.ResultVisitor;
import com.heaven7.java.visitor.anno.Nullable;
import com.heaven7.java.visitor.collection.IterateControl.Callback;
import com.heaven7.java.visitor.internal.InternalUtil;
import com.heaven7.java.visitor.internal.OperationPools;
import com.heaven7.java.visitor.internal.state.IterateState;
import com.heaven7.java.visitor.item.*;
import com.heaven7.java.visitor.util.Collections2;
import com.heaven7.java.visitor.util.Observer;
import com.heaven7.java.visitor.util.SparseArray;
import com.heaven7.java.visitor.util.Throwables;
import java.util.*;
import static com.heaven7.java.visitor.collection.Operation.*;
import static com.heaven7.java.visitor.util.Predicates.isTrue;
import static com.heaven7.java.visitor.util.Throwables.checkEmpty;
import static com.heaven7.java.visitor.util.Throwables.checkNull;
package com.heaven7.java.visitor.collection;




/**
 *
 * priority: delete > filter > update > insert.
 *
 * @author heaven7
 *
 * @param <T>
 *            the type of element
 * @see ListVisitServiceImpl
 */
public class CollectionVisitServiceImpl<T> extends AbstractCollectionVisitService<T>
		implements CollectionVisitService<T> {

	//protected static final boolean DEBUG = true;

	private final Collection<T> mCollection;

	/** the ordered operate */
	private List<Integer> mOrderOps;
	/** the intercept operate */
	private List<Integer> mInterceptOps;

	private final IterateControl<CollectionVisitService<T>> mControl;
	/** the operate interceptor */
	private final GroupOperateInterceptor mGroupInterceptor = new GroupOperateInterceptor();

	/** the all Operation/operate of insert in iteration */
	private List<CollectionOperation<T>> mInsertOps;
	/** the all Operation/operate of final insert after iteration */
	private List<CollectionOperation<T>> mFinalInsertOps;
	/** the all Operation/operate of update in iteration */
	private List<CollectionOperation<T>> mUpdateOps;
	/** the Operation/operate of filter */
	private CollectionOperation<T> mFilterOp;
	/** the Operation/operate of delete or remove. */
	private CollectionOperation<T> mDeleteOp;
	/** the operate of insert if not exist. */
	private CollectionOperation<T> mInsertIfNotExistOp;
	/** the operate of delete if exist. */
	private CollectionOperation<T> mDeleteIfExistOp;

	private IterationInfo mIterationInfo;

	/** the flags of clean up, default is {@linkplain VisitService#FLAG_ALL} */
	private int mCleanUpFlags = FLAG_ALL;

	/* protected */ CollectionVisitServiceImpl(Collection<T> collection) {
		super();
		checkNull(collection);
		this.mCollection = collection;
		mControl = IterateControl.<CollectionVisitService<T>>create(this, new ControlCallbackImpl());
		// init default
		mControl.begin().end();
	}

	// ===============================================================================


	@Override
	public CollectionVisitService<Long> mapLong() {
		return map(new ResultVisitor<T, Long>() {
			@Override
			public Long visit(T t, Object param) {
				if(t instanceof ILongItem){
					return ((ILongItem) t).getLong();
				}
				return null;
			}
		});
	}

	@Override
	public CollectionVisitService<Byte> mapByte() {
		return map(new ResultVisitor<T, Byte>() {
			@Override
			public Byte visit(T t, Object param) {
				if(t instanceof IByteItem){
					return ((IByteItem) t).getByte();
				}
				return null;
			}
		});
	}

	@Override
	public CollectionVisitService<Integer> mapInt() {
		return map(new ResultVisitor<T, Integer>() {
			@Override
			public Integer visit(T t, Object param) {
				if(t instanceof IIntItem){
					return ((IIntItem) t).getInt();
				}
				return null;
			}
		});
	}

	@Override
	public CollectionVisitService<Float> mapFloat() {
		return map(new ResultVisitor<T, Float>() {
			@Override
			public Float visit(T t, Object param) {
				if(t instanceof IFloatItem){
					return ((IFloatItem) t).getFloat();
				}
				return null;
			}
		});
	}

	@Override
	public CollectionVisitService<Double> mapDouble() {
		return map(new ResultVisitor<T, Double>() {
			@Override
			public Double visit(T t, Object param) {
				if(t instanceof IDoubleItem){
					return ((IDoubleItem) t).getDouble();
				}
				return null;
			}
		});
	}
	@Override
	public CollectionVisitService<String> mapString() {
		return map(new ResultVisitor<T, String>() {
			@Override
			public String visit(T t, Object param) {
				if(t instanceof IStringItem){
					return ((IStringItem) t).getString();
				}
				return null;
			}
		});
	}
	@Override
	public CollectionVisitService<List<T>> merge() {
		ArrayList<List<T>> result = new ArrayList<>();
		result.add(new ArrayList<>(mCollection));
		return VisitServices.from(result);
	}
	@SuppressWarnings("unchecked")
	public<R> CollectionVisitService<R> separate(){
		if(mCollection.isEmpty()){
			return VisitServices.from(new ArrayList<R>());
		}
		ArrayList<T> ts = new ArrayList<>(mCollection);
		if(ts.get(0) instanceof Collection){
			List<R> list = new ArrayList<>();
			int size = ts.size();
			try{
				for (int i = 0; i < size; i++) {
					Collection<R> t = (Collection<R>) ts.get(0);
					list.addAll(t);
				}
			}catch (ClassCastException e){
				throw new IllegalStateException("for separate. element must impl Collection, And also type mus be target type.");
			}
			return VisitServices.from(list);
		}else {
			throw new IllegalStateException("for separate. element must impl Collection.");
		}
	}

	@Override
	public int size() {
		return mCollection.size();
	}

	@Override
	public CollectionVisitService<T> clear() {
		mCollection.clear();
		return this;
	}

	@Override
	public CollectionVisitService<T> addIfNotExist(T newT, Observer<T, Void> observer) {
		try {
			if (!mCollection.contains(newT) && mCollection.add(newT)) {
				observer.onSuccess(null, null);
			} else {
				observer.onFailed(null, newT);
			}
		} catch (Exception e) {
			observer.onThrowable(null, newT, e);
		}
		return this;
	}

	@Override
	public CollectionVisitService<T> addIfNotExist(T newT) {
		if (!mCollection.contains(newT)) {
			mCollection.add(newT);
		}
		return this;
	}

	@Override
	public CollectionVisitService<T> removeIfExist(T newT) {
		mCollection.remove(newT);
		return this;
	}

	@Override
	public CollectionVisitService<T> removeIfExist(T newT, Observer<T, Void> observer) {
		try {
			if (mCollection.remove(newT)) {
				observer.onSuccess(null, null);
			} else {
				observer.onFailed(null, newT);
			}
		} catch (Exception e) {
			observer.onThrowable(null, newT, e);
		}
		return this;
	}

	// =============================================================================//
	@Override
	public <R> R visitForResult(@Nullable Object param, PredicateVisitor<? super T> predicate,