/* dIntProg Browser. A webbrowser written in Java.
 * Copyright (C) 2001 Martin Geisler <gimpster@gimpster.com>
 *  
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * 
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/** A set of non-<code>null</code> objects. The set is based on an
 *  array, and will grow as needed to accomodate additional items. */
public class Set {

    private Object[] set;
    private int count = 0;

    /** Constructs a set with an initial size of 32 elements. */
    public Set() {
        this(32);
    }

    /** Constructs a set with room for <code>size</code> elements. The
     *  set will grow as needed.
     *  @param size the initial size. */
    public Set(int size) {
        if (size < 2) {
            size = 2;
        }
        set = new Object[size];
    }

    /** Is the set empty?
     *  @return <code>true</code> if the set is empty. */
    public boolean empty() {
        return (count == 0);
    }

    /** Compares <code>obj</code> to the item is the set to determine
     *  if <code>obj</code> is already a member of the set. The
     *  objects are compared using <code>equals</code>.
     *  @param obj the object to test.
     *  @return <code>true</code> if the object is already a member.
     *  */
    public boolean member(Object obj) {
        for (int i = 0; i < count; i = i + 1) {
            if (set[i].equals(obj)) {
                return true;
            }
        }
        return false;
    }

    /** Add an object to the set. The object is only added if it's
     *  non-<code>null</code>. */
    public void add(Object obj) {
        if (obj != null && !member(obj)) {
            if (count == set.length) {
                grow();
            }
            set[count] = obj;
            count = count + 1;
        }
    }

    /** Clears the set. */
    public void clear() {
        count = 0;
    }

    /** Enlarges the set. The underlying array is doubled in length. */
    private void grow() {
        Object[] tmp = new Object[set.length * 2];
        System.arraycopy(set, 0, tmp, 0, set.length);
        set = tmp;
    }

}