OneItemSet.java Source code

Java tutorial

Introduction

Here is the source code for OneItemSet.java

Source

/* $Id$
 *
 * Behavior Protocols Tools - Parsers, Transformations
 * Copyright (C) 2006-2007  DSRG, Charles University in Prague
 *                          http://dsrg.mff.cuni.cz/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 *
 */

import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *
 * @author thorm
 */
public class OneItemSet<E> extends AbstractCollection<E> implements Serializable {

    public boolean add(E i) {
        if (item == i) {
            return false;
        }
        if (item == null) {
            item = i;
            return true;
        }
        throw new IllegalArgumentException();
    }

    public Iterator<E> iterator() {
        return new Iterator() {
            public boolean hasNext() {
                return hasNxt;
            }

            public E next() {
                if (hasNxt) {
                    hasNxt = false;
                    return item;
                }
                throw new NoSuchElementException();
            }

            public void remove() {
                item = null;
            }

            boolean hasNxt = true;
        };
    }

    public int size() {
        return (item == null) ? 0 : 1;
    }

    public int hashCode() {
        return item.hashCode();
    }

    public boolean equals(Object o) {
        return (o instanceof OneItemSet) && item.equals(((OneItemSet) o).item);
    }

    E item;
}