blob: 1648ec925c62850ca75bcaf274123bee577e9e7c [file] [log] [blame]
Dianne Hackborn21ab6f42013-06-10 15:59:15 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.util;
18
19import java.lang.reflect.Array;
20import java.util.Collection;
21import java.util.Iterator;
22import java.util.Map;
23import java.util.Set;
24
25/**
26 * ArraySet is a generic set data structure that is designed to be more memory efficient than a
27 * traditional {@link java.util.HashSet}. The design is very similar to
28 * {@link ArrayMap}, with all of the caveats described there. This implementation is
29 * separate from ArrayMap, however, so the Object array contains only one item for each
30 * entry in the set (instead of a pair for a mapping).
31 *
32 * <p>Note that this implementation is not intended to be appropriate for data structures
33 * that may contain large numbers of items. It is generally slower than a traditional
34 * HashSet, since lookups require a binary search and adds and removes require inserting
35 * and deleting entries in the array. For containers holding up to hundreds of items,
Dianne Hackbornb993f412013-07-12 17:46:45 -070036 * the performance difference is not significant, less than 50%.</p>
Dianne Hackborn21ab6f42013-06-10 15:59:15 -070037 *
38 * <p><b>Note:</b> unlike {@link java.util.HashSet}, this container does not support
39 * null values.</p>
40 *
41 * <p>Because this container is intended to better balance memory use, unlike most other
42 * standard Java containers it will shrink its array as items are removed from it. Currently
43 * you have no control over this shrinking -- if you set a capacity and then remove an
44 * item, it may reduce the capacity to better match the current size. In the future an
Dianne Hackbornb993f412013-07-12 17:46:45 -070045 * explicit call to set the capacity should turn off this aggressive shrinking behavior.</p>
Dianne Hackborn21ab6f42013-06-10 15:59:15 -070046 *
47 * @hide
48 */
49public final class ArraySet<E> implements Collection<E>, Set<E> {
50 private static final boolean DEBUG = false;
51 private static final String TAG = "ArraySet";
52
53 /**
54 * The minimum amount by which the capacity of a ArraySet will increase.
55 * This is tuned to be relatively space-efficient.
56 */
57 private static final int BASE_SIZE = 4;
58
59 /**
60 * Maximum number of entries to have in array caches.
61 */
62 private static final int CACHE_SIZE = 10;
63
64 /**
65 * Caches of small array objects to avoid spamming garbage. The cache
66 * Object[] variable is a pointer to a linked list of array objects.
67 * The first entry in the array is a pointer to the next array in the
68 * list; the second entry is a pointer to the int[] hash code array for it.
69 */
70 static Object[] mBaseCache;
71 static int mBaseCacheSize;
72 static Object[] mTwiceBaseCache;
73 static int mTwiceBaseCacheSize;
74
75 int[] mHashes;
76 Object[] mArray;
77 int mSize;
78 MapCollections<E, E> mCollections;
79
80 private int indexOf(Object key, int hash) {
81 final int N = mSize;
82
83 // Important fast case: if nothing is in here, nothing to look for.
84 if (N == 0) {
85 return ~0;
86 }
87
Dianne Hackborn3e82ba12013-07-16 13:23:55 -070088 int index = ContainerHelpers.binarySearch(mHashes, N, hash);
Dianne Hackborn21ab6f42013-06-10 15:59:15 -070089
90 // If the hash code wasn't found, then we have no entry for this key.
91 if (index < 0) {
92 return index;
93 }
94
95 // If the key at the returned index matches, that's what we want.
96 if (mArray[index].equals(key)) {
97 return index;
98 }
99
100 // Search for a matching key after the index.
101 int end;
102 for (end = index + 1; end < N && mHashes[end] == hash; end++) {
103 if (mArray[end].equals(key)) return end;
104 }
105
106 // Search for a matching key before the index.
107 for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {
108 if (mArray[i].equals(key)) return i;
109 }
110
111 // Key not found -- return negative value indicating where a
112 // new entry for this key should go. We use the end of the
113 // hash chain to reduce the number of array entries that will
114 // need to be copied when inserting.
115 return ~end;
116 }
117
118 private void allocArrays(final int size) {
119 if (size == (BASE_SIZE*2)) {
120 synchronized (ArraySet.class) {
121 if (mTwiceBaseCache != null) {
122 final Object[] array = mTwiceBaseCache;
123 mArray = array;
124 mTwiceBaseCache = (Object[])array[0];
125 mHashes = (int[])array[1];
126 array[0] = array[1] = null;
127 mTwiceBaseCacheSize--;
128 if (DEBUG) Log.d(TAG, "Retrieving 2x cache " + mHashes
129 + " now have " + mTwiceBaseCacheSize + " entries");
130 return;
131 }
132 }
133 } else if (size == BASE_SIZE) {
134 synchronized (ArraySet.class) {
135 if (mBaseCache != null) {
136 final Object[] array = mBaseCache;
137 mArray = array;
138 mBaseCache = (Object[])array[0];
139 mHashes = (int[])array[1];
140 array[0] = array[1] = null;
141 mBaseCacheSize--;
142 if (DEBUG) Log.d(TAG, "Retrieving 1x cache " + mHashes
143 + " now have " + mBaseCacheSize + " entries");
144 return;
145 }
146 }
147 }
148
149 mHashes = new int[size];
150 mArray = new Object[size];
151 }
152
153 private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
154 if (hashes.length == (BASE_SIZE*2)) {
155 synchronized (ArraySet.class) {
156 if (mTwiceBaseCacheSize < CACHE_SIZE) {
157 array[0] = mTwiceBaseCache;
158 array[1] = hashes;
159 for (int i=size-1; i>=2; i--) {
160 array[i] = null;
161 }
162 mTwiceBaseCache = array;
163 mTwiceBaseCacheSize++;
164 if (DEBUG) Log.d(TAG, "Storing 2x cache " + array
165 + " now have " + mTwiceBaseCacheSize + " entries");
166 }
167 }
168 } else if (hashes.length == BASE_SIZE) {
169 synchronized (ArraySet.class) {
170 if (mBaseCacheSize < CACHE_SIZE) {
171 array[0] = mBaseCache;
172 array[1] = hashes;
173 for (int i=size-1; i>=2; i--) {
174 array[i] = null;
175 }
176 mBaseCache = array;
177 mBaseCacheSize++;
178 if (DEBUG) Log.d(TAG, "Storing 1x cache " + array
179 + " now have " + mBaseCacheSize + " entries");
180 }
181 }
182 }
183 }
184
185 /**
186 * Create a new empty ArraySet. The default capacity of an array map is 0, and
187 * will grow once items are added to it.
188 */
189 public ArraySet() {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700190 mHashes = ContainerHelpers.EMPTY_INTS;
191 mArray = ContainerHelpers.EMPTY_OBJECTS;
Dianne Hackborn21ab6f42013-06-10 15:59:15 -0700192 mSize = 0;
193 }
194
195 /**
196 * Create a new ArraySet with a given initial capacity.
197 */
198 public ArraySet(int capacity) {
199 if (capacity == 0) {
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700200 mHashes = ContainerHelpers.EMPTY_INTS;
201 mArray = ContainerHelpers.EMPTY_OBJECTS;
Dianne Hackborn21ab6f42013-06-10 15:59:15 -0700202 } else {
203 allocArrays(capacity);
204 }
205 mSize = 0;
206 }
207
208 /**
209 * Create a new ArraySet with the mappings from the given ArraySet.
210 */
211 public ArraySet(ArraySet set) {
212 this();
213 if (set != null) {
214 addAll(set);
215 }
216 }
217
218
219 /**
220 * Make the array map empty. All storage is released.
221 */
222 @Override
223 public void clear() {
224 if (mSize != 0) {
225 freeArrays(mHashes, mArray, mSize);
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700226 mHashes = ContainerHelpers.EMPTY_INTS;
227 mArray = ContainerHelpers.EMPTY_OBJECTS;
Dianne Hackborn21ab6f42013-06-10 15:59:15 -0700228 mSize = 0;
229 }
230 }
231
232 /**
233 * Ensure the array map can hold at least <var>minimumCapacity</var>
234 * items.
235 */
236 public void ensureCapacity(int minimumCapacity) {
237 if (mHashes.length < minimumCapacity) {
238 final int[] ohashes = mHashes;
239 final Object[] oarray = mArray;
240 allocArrays(minimumCapacity);
241 if (mSize > 0) {
242 System.arraycopy(ohashes, 0, mHashes, 0, mSize);
243 System.arraycopy(oarray, 0, mArray, 0, mSize);
244 }
245 freeArrays(ohashes, oarray, mSize);
246 }
247 }
248
249 /**
250 * Check whether a value exists in the set.
251 *
252 * @param key The value to search for.
253 * @return Returns true if the value exists, else false.
254 */
255 @Override
256 public boolean contains(Object key) {
257 return indexOf(key, key.hashCode()) >= 0;
258 }
259
260 /**
261 * Return the value at the given index in the array.
262 * @param index The desired index, must be between 0 and {@link #size()}-1.
263 * @return Returns the value stored at the given index.
264 */
265 public E valueAt(int index) {
266 return (E)mArray[index];
267 }
268
269 /**
270 * Return true if the array map contains no items.
271 */
272 @Override
273 public boolean isEmpty() {
274 return mSize <= 0;
275 }
276
277 /**
278 * Adds the specified object to this set. The set is not modified if it
279 * already contains the object.
280 *
281 * @param value the object to add.
282 * @return {@code true} if this set is modified, {@code false} otherwise.
283 * @throws ClassCastException
284 * when the class of the object is inappropriate for this set.
285 */
286 @Override
287 public boolean add(E value) {
288 final int hash = value.hashCode();
289 int index = indexOf(value, hash);
290 if (index >= 0) {
291 return false;
292 }
293
294 index = ~index;
295 if (mSize >= mHashes.length) {
296 final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))
297 : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);
298
299 if (DEBUG) Log.d(TAG, "add: grow from " + mHashes.length + " to " + n);
300
301 final int[] ohashes = mHashes;
302 final Object[] oarray = mArray;
303 allocArrays(n);
304
305 if (mHashes.length > 0) {
306 if (DEBUG) Log.d(TAG, "add: copy 0-" + mSize + " to 0");
307 System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);
308 System.arraycopy(oarray, 0, mArray, 0, oarray.length);
309 }
310
311 freeArrays(ohashes, oarray, mSize);
312 }
313
314 if (index < mSize) {
315 if (DEBUG) Log.d(TAG, "add: move " + index + "-" + (mSize-index)
316 + " to " + (index+1));
317 System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);
318 System.arraycopy(mArray, index, mArray, index + 1, mSize - index);
319 }
320
321 mHashes[index] = hash;
322 mArray[index] = value;
323 mSize++;
324 return true;
325 }
326
327 /**
328 * Perform a {@link #add(Object)} of all values in <var>array</var>
329 * @param array The array whose contents are to be retrieved.
330 */
331 public void putAll(ArraySet<? extends E> array) {
332 final int N = array.mSize;
333 ensureCapacity(mSize + N);
334 if (mSize == 0) {
335 if (N > 0) {
336 System.arraycopy(array.mHashes, 0, mHashes, 0, N);
337 System.arraycopy(array.mArray, 0, mArray, 0, N);
338 mSize = N;
339 }
340 } else {
341 for (int i=0; i<N; i++) {
342 add(array.valueAt(i));
343 }
344 }
345 }
346
347 /**
348 * Removes the specified object from this set.
349 *
350 * @param object the object to remove.
351 * @return {@code true} if this set was modified, {@code false} otherwise.
352 */
353 @Override
354 public boolean remove(Object object) {
355 int index = indexOf(object, object.hashCode());
356 if (index >= 0) {
357 removeAt(index);
358 return true;
359 }
360 return false;
361 }
362
363 /**
364 * Remove the key/value mapping at the given index.
365 * @param index The desired index, must be between 0 and {@link #size()}-1.
366 * @return Returns the value that was stored at this index.
367 */
368 public E removeAt(int index) {
369 final E old = (E)mArray[index];
370 if (mSize <= 1) {
371 // Now empty.
372 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0");
373 freeArrays(mHashes, mArray, mSize);
Dianne Hackborn3e82ba12013-07-16 13:23:55 -0700374 mHashes = ContainerHelpers.EMPTY_INTS;
375 mArray = ContainerHelpers.EMPTY_OBJECTS;
Dianne Hackborn21ab6f42013-06-10 15:59:15 -0700376 mSize = 0;
377 } else {
378 if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) {
379 // Shrunk enough to reduce size of arrays. We don't allow it to
380 // shrink smaller than (BASE_SIZE*2) to avoid flapping between
381 // that and BASE_SIZE.
382 final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2);
383
384 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n);
385
386 final int[] ohashes = mHashes;
387 final Object[] oarray = mArray;
388 allocArrays(n);
389
390 mSize--;
391 if (index > 0) {
392 if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0");
393 System.arraycopy(ohashes, 0, mHashes, 0, index);
394 System.arraycopy(oarray, 0, mArray, 0, index);
395 }
396 if (index < mSize) {
397 if (DEBUG) Log.d(TAG, "remove: copy from " + (index+1) + "-" + mSize
398 + " to " + index);
399 System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);
400 System.arraycopy(oarray, index + 1, mArray, index, mSize - index);
401 }
402 } else {
403 mSize--;
404 if (index < mSize) {
405 if (DEBUG) Log.d(TAG, "remove: move " + (index+1) + "-" + mSize
406 + " to " + index);
407 System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);
408 System.arraycopy(mArray, index + 1, mArray, index, mSize - index);
409 }
410 mArray[mSize] = null;
411 }
412 }
413 return old;
414 }
415
416 /**
417 * Return the number of items in this array map.
418 */
419 @Override
420 public int size() {
421 return mSize;
422 }
423
424 @Override
425 public Object[] toArray() {
426 Object[] result = new Object[mSize];
427 System.arraycopy(mArray, 0, result, 0, mSize);
428 return result;
429 }
430
431 @Override
432 public <T> T[] toArray(T[] array) {
433 if (array.length < mSize) {
434 @SuppressWarnings("unchecked") T[] newArray
435 = (T[]) Array.newInstance(array.getClass().getComponentType(), mSize);
436 array = newArray;
437 }
438 System.arraycopy(mArray, 0, array, 0, mSize);
439 if (array.length > mSize) {
440 array[mSize] = null;
441 }
442 return array;
443 }
444
445 /**
446 * {@inheritDoc}
447 *
448 * <p>This implementation returns false if the object is not a set, or
449 * if the sets have different sizes. Otherwise, for each value in this
450 * set, it checks to make sure the value also exists in the other set.
451 * If any value doesn't exist, the method returns false; otherwise, it
452 * returns true.
453 */
454 @Override
455 public boolean equals(Object object) {
456 if (this == object) {
457 return true;
458 }
459 if (object instanceof Set) {
460 Set<?> set = (Set<?>) object;
461 if (size() != set.size()) {
462 return false;
463 }
464
465 try {
466 for (int i=0; i<mSize; i++) {
467 E mine = valueAt(i);
468 if (!set.contains(mine)) {
469 return false;
470 }
471 }
472 } catch (NullPointerException ignored) {
473 return false;
474 } catch (ClassCastException ignored) {
475 return false;
476 }
477 return true;
478 }
479 return false;
480 }
481
482 /**
483 * {@inheritDoc}
484 */
485 @Override
486 public int hashCode() {
487 final int[] hashes = mHashes;
488 int result = 0;
489 for (int i = 0, s = mSize; i < s; i++) {
490 result += hashes[i];
491 }
492 return result;
493 }
494
Dianne Hackborna17c0f52013-06-20 18:59:11 -0700495 /**
496 * {@inheritDoc}
497 *
498 * <p>This implementation composes a string by iterating over its values. If
499 * this set contains itself as a value, the string "(this Set)"
500 * will appear in its place.
501 */
502 @Override
503 public String toString() {
504 if (isEmpty()) {
505 return "{}";
506 }
507
508 StringBuilder buffer = new StringBuilder(mSize * 14);
509 buffer.append('{');
510 for (int i=0; i<mSize; i++) {
511 if (i > 0) {
512 buffer.append(", ");
513 }
514 Object value = valueAt(i);
515 if (value != this) {
516 buffer.append(value);
517 } else {
518 buffer.append("(this Set)");
519 }
520 }
521 buffer.append('}');
522 return buffer.toString();
523 }
524
Dianne Hackborn21ab6f42013-06-10 15:59:15 -0700525 // ------------------------------------------------------------------------
526 // Interop with traditional Java containers. Not as efficient as using
527 // specialized collection APIs.
528 // ------------------------------------------------------------------------
529
530 private MapCollections<E, E> getCollection() {
531 if (mCollections == null) {
532 mCollections = new MapCollections<E, E>() {
533 @Override
534 protected int colGetSize() {
535 return mSize;
536 }
537
538 @Override
539 protected Object colGetEntry(int index, int offset) {
540 return mArray[index];
541 }
542
543 @Override
544 protected int colIndexOfKey(Object key) {
545 return indexOf(key, key.hashCode());
546 }
547
548 @Override
549 protected int colIndexOfValue(Object value) {
550 return indexOf(value, value.hashCode());
551 }
552
553 @Override
554 protected Map<E, E> colGetMap() {
555 throw new UnsupportedOperationException("not a map");
556 }
557
558 @Override
559 protected void colPut(E key, E value) {
560 add(key);
561 }
562
563 @Override
564 protected E colSetValue(int index, E value) {
565 throw new UnsupportedOperationException("not a map");
566 }
567
568 @Override
569 protected void colRemoveAt(int index) {
570 removeAt(index);
571 }
572
573 @Override
574 protected void colClear() {
575 clear();
576 }
577 };
578 }
579 return mCollections;
580 }
581
582 @Override
583 public Iterator<E> iterator() {
584 return getCollection().getKeySet().iterator();
585 }
586
587 @Override
588 public boolean containsAll(Collection<?> collection) {
589 Iterator<?> it = collection.iterator();
590 while (it.hasNext()) {
591 if (!contains(it.next())) {
592 return false;
593 }
594 }
595 return true;
596 }
597
598 @Override
599 public boolean addAll(Collection<? extends E> collection) {
600 ensureCapacity(mSize + collection.size());
601 boolean added = false;
602 for (E value : collection) {
603 added |= add(value);
604 }
605 return added;
606 }
607
608 @Override
609 public boolean removeAll(Collection<?> collection) {
610 boolean removed = false;
611 for (Object value : collection) {
612 removed |= remove(value);
613 }
614 return removed;
615 }
616
617 @Override
618 public boolean retainAll(Collection<?> collection) {
619 boolean removed = false;
620 for (int i=mSize-1; i>=0; i--) {
621 if (!collection.contains(mArray[i])) {
622 removeAt(i);
623 removed = true;
624 }
625 }
626 return removed;
627 }
628}