/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.collection;

import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import net.ranides.assira.collection.arrays.ArrayAllocator;
import net.ranides.assira.collection.arrays.ArrayUtils;

public abstract class ACollection<K> extends AbstractCollection<K> implements Collection<K> {

    protected ACollection() {
        // protected constructor
    }

    @Override
    public Object[] toArray() {
        Object[] target = new Object[size()];
        ArrayUtils.collect(iterator(), target);
        return target;
    }

    @Override
    public <T> T[] toArray(T[] target) {
        T[] result = target;
        int n = size();
        if (result.length < n) {
            result = ArrayAllocator.forPrototype(result, n);
        }
        ArrayUtils.collect(iterator(), result);
        return result;
    }

    @Override
    public String toString() {
        Iterator<K> itr = iterator();
        if ( !itr.hasNext() ) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder();
        builder.append('[');
        for (;;) {
            K item = itr.next();
            builder.append(item == this ? "(this Collection)" : item);
            if ( !itr.hasNext() ) {
                return builder.append(']').toString();
            }
            builder.append(", ");
        }
    }

}
