001package org.biojava.utils;
002
003import java.util.AbstractSet;
004import java.util.HashSet;
005import java.util.Iterator;
006import java.util.Set;
007
008/**
009 *
010 *
011 * @author Matthew Pocock
012 */
013public class MergingSet
014        extends AbstractSet
015{
016  private final Set sets;
017  private Set modifiable;
018
019  public static MergingSet merge(Set first, Set seccond)
020  {
021    MergingSet ms = new MergingSet();
022    ms.add(first);
023    ms.add(seccond);
024    return ms;
025  }
026
027  public static MergingSet modifiableMerge()
028  {
029    MergingSet ms = new MergingSet();
030    ms.modifiable = new HashSet();
031    ms.addSet(ms.modifiable);
032    return ms;
033  }
034
035  public static MergingSet modifiableMerge(Set original)
036  {
037    MergingSet ms = new MergingSet();
038    ms.modifiable = new HashSet();
039    ms.addSet(ms.modifiable);
040    ms.addSet(original);
041    return ms;
042  }
043
044  public MergingSet() {
045    this.sets = new SmallSet();
046  }
047
048  public MergingSet(Set sets) {
049    this.sets = new SmallSet(sets);
050  }
051
052  public void addSet(Set set) {
053    sets.add(set);
054  }
055
056  public boolean removeSet(Set set) {
057    if(set == modifiable) {
058      throw new IllegalArgumentException(
059              "Can't remove the set that contains modifications");
060    }
061    return sets.remove(set);
062  }
063
064  public Set getModifiable()
065  {
066    return modifiable;
067  }
068
069  public int size() {
070    int size = 0;
071
072    for(Iterator i = sets.iterator(); i.hasNext(); ) {
073      Set s = (Set) i.next();
074      size += s.size();
075    }
076
077    return size;
078  }
079
080  public boolean contains(Object o) {
081    for (Iterator i = sets.iterator(); i.hasNext();) {
082      Set s = (Set) i.next();
083      if(s.contains(o)) {
084        return true;
085      }
086    }
087
088    return false;
089  }
090
091  public Iterator iterator() {
092    return new MergingIterator(sets.iterator());
093  }
094
095  public boolean add(Object o)
096  {
097    if(modifiable == null) {
098      throw new UnsupportedOperationException();
099    }
100
101    return modifiable.add(o);
102  }
103
104  public boolean remove(Object o)
105  {
106    if(modifiable == null) {
107      throw new UnsupportedOperationException();
108    }
109
110    if(this.contains(o) && !modifiable.contains(o)) {
111      throw new IllegalArgumentException(
112              "Can't remove items not added to this merged view");
113    }
114
115    return modifiable.remove(o);
116  }
117}