2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
6 * The Java Pathfinder core (jpf-core) platform is licensed under the
7 * Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0.
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 package gov.nasa.jpf.util;
21 import java.util.Iterator;
22 import java.util.NoSuchElementException;
25 * simple identity set for objects
26 * we don't sort&bisect, assuming the number of entries will be small
27 * be aware this doesn't scale to large sets
29 public class IdentityArrayObjectSet<E> implements IdentityObjectSet<E> {
31 static final int DEFAULT_CAPACITY = 4;
33 private class StoreOrderIterator implements Iterator<E> {
37 public void remove() {
41 System.arraycopy(elements, next, elements, idx, size-idx);
49 public boolean hasNext() {
56 return (E) elements[next++];
58 throw new NoSuchElementException();
64 protected Object[] elements;
66 public IdentityArrayObjectSet(){
67 // nothing, elements allocated on demand
70 public IdentityArrayObjectSet (int initialCapacity){
71 elements = new Object[initialCapacity];
74 public IdentityArrayObjectSet (E initialElement){
75 elements = new Object[DEFAULT_CAPACITY];
77 elements[0] = initialElement;
86 public boolean isEmpty(){
91 public boolean add (E obj){
92 for (int i=0; i<size; i++){
93 if (elements[i] == obj){
99 elements = new Object[DEFAULT_CAPACITY];
100 } else if (size == elements.length){
101 Object[] newElements = new Object[elements.length * 3 / 2];
102 System.arraycopy(elements, 0, newElements, 0, size);
103 elements = newElements;
106 elements[size] = obj;
112 public boolean contains (E obj){
113 for (int i=0; i<size; i++){
114 if (elements[i] == obj){
123 public boolean remove (E obj){
125 for (int i=0; i<len; i++){
126 if (elements[i] == obj){
133 System.arraycopy(elements, i+1, elements, i, len-i);
135 elements[len] = null; // avoid memory leak
147 public ObjectSet<E> clone(){
149 return (ObjectSet<E>)super.clone();
150 } catch (CloneNotSupportedException x){
157 public Iterator<E> iterator(){
158 return new StoreOrderIterator();
162 public String toString(){
163 StringBuilder sb = new StringBuilder(/*getClass().getName()*/);
165 for (int i=0; i<size; i++){
169 sb.append(elements[i]);
172 return sb.toString();