001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: ListableHashSet.java 77 2011-04-19 19:54:55Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.jibx;
009    
010    import java.util.Collection;
011    import java.util.LinkedHashSet;
012    
013    import org.jibx.runtime.JiBXException;
014    
015    /**
016     * {@link java.util.Set} implementation with these properties which make it suitable for use with JiBX:
017     * <ul>
018     * <li>Iteration order reflects addition order (this property is inherited from {@link LinkedHashSet})</li>
019     * <li>An {@link #addUnique} method that throws {@link JiBXException} if the item is already in the set
020     *  (suitable for use as a JiBX {@code add-method})</li>
021     * </ul>
022     *
023     * @since 1.0.64
024     */
025    @SuppressWarnings("serial")
026    public class ListableHashSet<E> extends LinkedHashSet<E> {
027    
028        public ListableHashSet() {
029        }
030    
031        public ListableHashSet(Collection<? extends E> c) {
032            super(c);
033        }
034    
035        public ListableHashSet(int initialCapacity) {
036            super(initialCapacity);
037        }
038    
039        public ListableHashSet(int initialCapacity, float loadFactor) {
040            super(initialCapacity, loadFactor);
041        }
042    
043        /**
044         * Add an item to a set while verifying that the item is not already in the set.
045         *
046         * @throws JiBXException if item is already in the set
047         */
048        public void addUnique(E item) throws JiBXException {
049            if (this.contains(item))
050                throw new JiBXException("duplicate item in set: " + item);
051            this.add(item);
052        }
053    }
054