001 /*
002 * SimpleArraySet.java
003 *
004 * Copyright (c) 2001, The University of Sheffield.
005 *
006 * This file is part of GATE (see http://gate.ac.uk/), and is free
007 * software, licenced under the GNU Library General Public License,
008 * Version 2, June 1991 (in the distribution as file licence.html,
009 * and also available at http://gate.ac.uk/gate/licence.html).
010 *
011 * D.Ognyanoff, 5/Nov/2001
012 *
013 * $Id: SimpleArraySet.java 8055 2007-01-23 19:20:43Z kwilliams $
014 */
015
016
017 package gate.util;
018
019 import java.io.Serializable;
020 import java.util.ArrayList;
021 import java.util.Arrays;
022 import java.util.Collection;
023
024
025 /**
026 * A specific *partial* implementation of the Set interface used for
027 * high performance and memory reduction on small sets. Used in
028 * gate.fsm.State, for example
029 */
030 public class SimpleArraySet<T> implements Serializable, Iterable<T>
031 {
032 /**
033 * The array storing the elements
034 */
035 Object[] theArray = null;
036
037 public int size()
038 {
039 return theArray == null ? 0 : theArray.length;
040 }
041
042 public Collection asCollection()
043 {
044 if (theArray == null) return new ArrayList();
045 return Arrays.asList(theArray);
046 }
047
048 public boolean add(T tr)
049 {
050 if (theArray == null)
051 {
052 theArray = new Object[1];
053 theArray[0] = tr;
054 } else {
055 int newsz = theArray.length+1;
056 int index = java.util.Arrays.binarySearch(theArray, tr);
057 if (index < 0)
058 {
059 index = ~index;
060 Object[] temp = new Object[newsz];
061 int i;
062 for (i = 0; i < index; i++)
063 {
064 temp[i] = theArray[i]; theArray[i] = null;
065 }
066 for (i = index+1; i<newsz; i++)
067 {
068 temp[i] = theArray[i-1]; theArray[i-1] = null;
069 }
070 temp[index] = tr;
071 theArray = temp;
072 } else {
073 theArray[index] = tr;
074 }
075 } // if initially empty
076 return true;
077 } // add
078
079 /**
080 * iterator
081 */
082 public java.util.Iterator<T> iterator()
083 {
084 if (theArray == null)
085 return new java.util.Iterator<T>()
086 {
087 public boolean hasNext() {return false;}
088 public T next() { return null; }
089 public void remove() {}
090 };
091 else
092 return new java.util.Iterator<T>()
093 {
094 int count = 0;
095 public boolean hasNext()
096 {
097 if (theArray == null)
098 throw new RuntimeException("");
099 return count < theArray.length;
100 }
101 public T next() {
102 if (theArray == null)
103 throw new RuntimeException("");
104 return (T) theArray[count++];
105 }
106 public void remove() {}
107 }; // anonymous iterator
108 } // iterator
109
110 } // SimpleArraySet
|