1   /*
2    *  SimpleArraySet.java
3    *
4    *  Copyright (c) 2001, The University of Sheffield.
5    *
6    *  This file is part of GATE (see http://gate.ac.uk/), and is free
7    *  software, licenced under the GNU Library General Public License,
8    *  Version 2, June 1991 (in the distribution as file licence.html,
9    *  and also available at http://gate.ac.uk/gate/licence.html).
10   *
11   *   D.Ognyanoff, 5/Nov/2001
12   *
13   *  $Id: SimpleArraySet.java,v 1.1 2001/11/05 16:16:16 nasso Exp $
14   */
15  
16  
17  package gate.util;
18  
19  import java.util.*;
20  
21  /**
22   * A specific *partial* implementation of the Set interface used for
23   * high performance and memory reduction on small sets. Used in
24   * gate.fsm.State, for example
25   */
26  public class SimpleArraySet
27  {
28    /**
29     * The array storing the elements
30     */
31    Object[] theArray = null;
32  
33    public boolean add(Object tr)
34    {
35      if (theArray == null)
36      {
37        theArray = new Object[1];
38        theArray[0] = tr;
39      } else {
40        int newsz = theArray.length+1;
41        int index = java.util.Arrays.binarySearch(theArray, tr);
42        if (index < 0)
43        {
44          index = ~index;
45          Object[] temp = new Object[newsz];
46          int i;
47          for (i = 0; i < index; i++)
48          {
49            temp[i] = theArray[i]; theArray[i] = null;
50          }
51          for (i = index+1; i<newsz; i++)
52          {
53            temp[i] = theArray[i-1]; theArray[i-1] = null;
54          }
55          temp[index] = tr;
56          theArray = temp;
57        } else {
58          theArray[index] = tr;
59        }
60      } // if initially empty
61      return true;
62    } // add
63  
64    /**
65     * iterator
66     */
67    public java.util.Iterator iterator()
68    {
69      if (theArray == null)
70        return new java.util.Iterator()
71          {
72            public boolean hasNext() {return false;}
73            public Object next() { return null; }
74            public void remove() {}
75          };
76      else
77        return new java.util.Iterator()
78          {
79            int count = 0;
80            public boolean hasNext()
81            {
82              if (theArray == null)
83                throw new RuntimeException("");
84              return count < theArray.length;
85            }
86            public Object next() {
87              if (theArray == null)
88                throw new RuntimeException("");
89              return theArray[count++];
90            }
91            public void remove() {}
92          }; // anonymous iterator
93    } // iterator
94  
95  } // SimpleArraySet
96