1 /* 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 17 package android.util; 18 19 import android.annotation.Nullable; 20 import android.annotation.TestApi; 21 import android.compat.annotation.UnsupportedAppUsage; 22 23 import java.lang.reflect.Array; 24 import java.util.Arrays; 25 import java.util.Collection; 26 import java.util.ConcurrentModificationException; 27 import java.util.Iterator; 28 import java.util.Map; 29 import java.util.Set; 30 import java.util.function.Consumer; 31 import java.util.function.Predicate; 32 33 /** 34 * ArraySet is a generic set data structure that is designed to be more memory efficient than a 35 * traditional {@link java.util.HashSet}. The design is very similar to 36 * {@link ArrayMap}, with all of the caveats described there. This implementation is 37 * separate from ArrayMap, however, so the Object array contains only one item for each 38 * entry in the set (instead of a pair for a mapping). 39 * 40 * <p>Note that this implementation is not intended to be appropriate for data structures 41 * that may contain large numbers of items. It is generally slower than a traditional 42 * HashSet, since lookups require a binary search and adds and removes require inserting 43 * and deleting entries in the array. For containers holding up to hundreds of items, 44 * the performance difference is not significant, less than 50%.</p> 45 * 46 * <p>Because this container is intended to better balance memory use, unlike most other 47 * standard Java containers it will shrink its array as items are removed from it. Currently 48 * you have no control over this shrinking -- if you set a capacity and then remove an 49 * item, it may reduce the capacity to better match the current size. In the future an 50 * explicit call to set the capacity should turn off this aggressive shrinking behavior.</p> 51 * 52 * <p>This structure is <b>NOT</b> thread-safe.</p> 53 */ 54 @android.ravenwood.annotation.RavenwoodKeepWholeClass 55 public final class ArraySet<E> implements Collection<E>, Set<E> { 56 private static final boolean DEBUG = false; 57 private static final String TAG = "ArraySet"; 58 59 /** 60 * The minimum amount by which the capacity of a ArraySet will increase. 61 * This is tuned to be relatively space-efficient. 62 */ 63 private static final int BASE_SIZE = 4; 64 65 /** 66 * Maximum number of entries to have in array caches. 67 */ 68 private static final int CACHE_SIZE = 10; 69 70 /** 71 * Caches of small array objects to avoid spamming garbage. The cache 72 * Object[] variable is a pointer to a linked list of array objects. 73 * The first entry in the array is a pointer to the next array in the 74 * list; the second entry is a pointer to the int[] hash code array for it. 75 */ 76 static Object[] sBaseCache; 77 static int sBaseCacheSize; 78 static Object[] sTwiceBaseCache; 79 static int sTwiceBaseCacheSize; 80 /** 81 * Separate locks for each cache since each can be accessed independently of the other without 82 * risk of a deadlock. 83 */ 84 private static final Object sBaseCacheLock = new Object(); 85 private static final Object sTwiceBaseCacheLock = new Object(); 86 87 private final boolean mIdentityHashCode; 88 @UnsupportedAppUsage(maxTargetSdk = 28) // Hashes are an implementation detail. Use public API. 89 int[] mHashes; 90 @UnsupportedAppUsage(maxTargetSdk = 28) // Storage is an implementation detail. Use public API. 91 Object[] mArray; 92 @UnsupportedAppUsage(maxTargetSdk = 28) // Use size() 93 int mSize; 94 private MapCollections<E, E> mCollections; 95 binarySearch(int[] hashes, int hash)96 private int binarySearch(int[] hashes, int hash) { 97 try { 98 return ContainerHelpers.binarySearch(hashes, mSize, hash); 99 } catch (ArrayIndexOutOfBoundsException e) { 100 throw new ConcurrentModificationException(); 101 } 102 } 103 104 105 @UnsupportedAppUsage(maxTargetSdk = 28) // Hashes are an implementation detail. Use indexOfKey(Object). indexOf(Object key, int hash)106 private int indexOf(Object key, int hash) { 107 final int N = mSize; 108 109 // Important fast case: if nothing is in here, nothing to look for. 110 if (N == 0) { 111 return ~0; 112 } 113 114 int index = binarySearch(mHashes, hash); 115 116 // If the hash code wasn't found, then we have no entry for this key. 117 if (index < 0) { 118 return index; 119 } 120 121 // If the key at the returned index matches, that's what we want. 122 if (key.equals(mArray[index])) { 123 return index; 124 } 125 126 // Search for a matching key after the index. 127 int end; 128 for (end = index + 1; end < N && mHashes[end] == hash; end++) { 129 if (key.equals(mArray[end])) return end; 130 } 131 132 // Search for a matching key before the index. 133 for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) { 134 if (key.equals(mArray[i])) return i; 135 } 136 137 // Key not found -- return negative value indicating where a 138 // new entry for this key should go. We use the end of the 139 // hash chain to reduce the number of array entries that will 140 // need to be copied when inserting. 141 return ~end; 142 } 143 144 @UnsupportedAppUsage(maxTargetSdk = 28) // Use indexOf(null) indexOfNull()145 private int indexOfNull() { 146 final int N = mSize; 147 148 // Important fast case: if nothing is in here, nothing to look for. 149 if (N == 0) { 150 return ~0; 151 } 152 153 int index = binarySearch(mHashes, 0); 154 155 // If the hash code wasn't found, then we have no entry for this key. 156 if (index < 0) { 157 return index; 158 } 159 160 // If the key at the returned index matches, that's what we want. 161 if (null == mArray[index]) { 162 return index; 163 } 164 165 // Search for a matching key after the index. 166 int end; 167 for (end = index + 1; end < N && mHashes[end] == 0; end++) { 168 if (null == mArray[end]) return end; 169 } 170 171 // Search for a matching key before the index. 172 for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) { 173 if (null == mArray[i]) return i; 174 } 175 176 // Key not found -- return negative value indicating where a 177 // new entry for this key should go. We use the end of the 178 // hash chain to reduce the number of array entries that will 179 // need to be copied when inserting. 180 return ~end; 181 } 182 183 @UnsupportedAppUsage(maxTargetSdk = 28) // Allocations are an implementation detail. allocArrays(final int size)184 private void allocArrays(final int size) { 185 if (size == (BASE_SIZE * 2)) { 186 synchronized (sTwiceBaseCacheLock) { 187 if (sTwiceBaseCache != null) { 188 final Object[] array = sTwiceBaseCache; 189 try { 190 mArray = array; 191 sTwiceBaseCache = (Object[]) array[0]; 192 mHashes = (int[]) array[1]; 193 if (mHashes != null) { 194 array[0] = array[1] = null; 195 sTwiceBaseCacheSize--; 196 if (DEBUG) { 197 Log.d(TAG, "Retrieving 2x cache " + Arrays.toString(mHashes) 198 + " now have " + sTwiceBaseCacheSize + " entries"); 199 } 200 return; 201 } 202 } catch (ClassCastException e) { 203 } 204 // Whoops! Someone trampled the array (probably due to not protecting 205 // their access with a lock). Our cache is corrupt; report and give up. 206 Slog.wtf(TAG, "Found corrupt ArraySet cache: [0]=" + array[0] 207 + " [1]=" + array[1]); 208 sTwiceBaseCache = null; 209 sTwiceBaseCacheSize = 0; 210 } 211 } 212 } else if (size == BASE_SIZE) { 213 synchronized (sBaseCacheLock) { 214 if (sBaseCache != null) { 215 final Object[] array = sBaseCache; 216 try { 217 mArray = array; 218 sBaseCache = (Object[]) array[0]; 219 mHashes = (int[]) array[1]; 220 if (mHashes != null) { 221 array[0] = array[1] = null; 222 sBaseCacheSize--; 223 if (DEBUG) { 224 Log.d(TAG, "Retrieving 1x cache " + Arrays.toString(mHashes) 225 + " now have " + sBaseCacheSize + " entries"); 226 } 227 return; 228 } 229 } catch (ClassCastException e) { 230 } 231 // Whoops! Someone trampled the array (probably due to not protecting 232 // their access with a lock). Our cache is corrupt; report and give up. 233 Slog.wtf(TAG, "Found corrupt ArraySet cache: [0]=" + array[0] 234 + " [1]=" + array[1]); 235 sBaseCache = null; 236 sBaseCacheSize = 0; 237 } 238 } 239 } 240 241 mHashes = new int[size]; 242 mArray = new Object[size]; 243 } 244 245 /** 246 * Make sure <b>NOT</b> to call this method with arrays that can still be modified. In other 247 * words, don't pass mHashes or mArray in directly. 248 */ 249 @UnsupportedAppUsage(maxTargetSdk = 28) // Allocations are an implementation detail. freeArrays(final int[] hashes, final Object[] array, final int size)250 private static void freeArrays(final int[] hashes, final Object[] array, final int size) { 251 if (hashes.length == (BASE_SIZE * 2)) { 252 synchronized (sTwiceBaseCacheLock) { 253 if (sTwiceBaseCacheSize < CACHE_SIZE) { 254 array[0] = sTwiceBaseCache; 255 array[1] = hashes; 256 for (int i = size - 1; i >= 2; i--) { 257 array[i] = null; 258 } 259 sTwiceBaseCache = array; 260 sTwiceBaseCacheSize++; 261 if (DEBUG) { 262 Log.d(TAG, "Storing 2x cache " + Arrays.toString(array) + " now have " 263 + sTwiceBaseCacheSize + " entries"); 264 } 265 } 266 } 267 } else if (hashes.length == BASE_SIZE) { 268 synchronized (sBaseCacheLock) { 269 if (sBaseCacheSize < CACHE_SIZE) { 270 array[0] = sBaseCache; 271 array[1] = hashes; 272 for (int i = size - 1; i >= 2; i--) { 273 array[i] = null; 274 } 275 sBaseCache = array; 276 sBaseCacheSize++; 277 if (DEBUG) { 278 Log.d(TAG, "Storing 1x cache " + Arrays.toString(array) + " now have " 279 + sBaseCacheSize + " entries"); 280 } 281 } 282 } 283 } 284 } 285 286 /** 287 * Create a new empty ArraySet. The default capacity of an array map is 0, and 288 * will grow once items are added to it. 289 */ ArraySet()290 public ArraySet() { 291 this(0, false); 292 } 293 294 /** 295 * Create a new ArraySet with a given initial capacity. 296 */ ArraySet(int capacity)297 public ArraySet(int capacity) { 298 this(capacity, false); 299 } 300 301 /** {@hide} */ ArraySet(int capacity, boolean identityHashCode)302 public ArraySet(int capacity, boolean identityHashCode) { 303 mIdentityHashCode = identityHashCode; 304 if (capacity == 0) { 305 mHashes = EmptyArray.INT; 306 mArray = EmptyArray.OBJECT; 307 } else { 308 allocArrays(capacity); 309 } 310 mSize = 0; 311 } 312 313 /** 314 * Create a new ArraySet with the mappings from the given ArraySet. 315 */ ArraySet(ArraySet<E> set)316 public ArraySet(ArraySet<E> set) { 317 this(); 318 if (set != null) { 319 addAll(set); 320 } 321 } 322 323 /** 324 * Create a new ArraySet with items from the given collection. 325 */ ArraySet(Collection<? extends E> set)326 public ArraySet(Collection<? extends E> set) { 327 this(); 328 if (set != null) { 329 addAll(set); 330 } 331 } 332 333 /** 334 * Create a new ArraySet with items from the given array 335 */ ArraySet(@ullable E[] array)336 public ArraySet(@Nullable E[] array) { 337 this(); 338 if (array != null) { 339 for (E value : array) { 340 add(value); 341 } 342 } 343 } 344 345 /** 346 * Make the array map empty. All storage is released. 347 */ 348 @Override clear()349 public void clear() { 350 if (mSize != 0) { 351 final int[] ohashes = mHashes; 352 final Object[] oarray = mArray; 353 final int osize = mSize; 354 mHashes = EmptyArray.INT; 355 mArray = EmptyArray.OBJECT; 356 mSize = 0; 357 freeArrays(ohashes, oarray, osize); 358 } 359 if (mSize != 0) { 360 throw new ConcurrentModificationException(); 361 } 362 } 363 364 /** 365 * Ensure the array map can hold at least <var>minimumCapacity</var> 366 * items. 367 */ ensureCapacity(int minimumCapacity)368 public void ensureCapacity(int minimumCapacity) { 369 final int oSize = mSize; 370 if (mHashes.length < minimumCapacity) { 371 final int[] ohashes = mHashes; 372 final Object[] oarray = mArray; 373 allocArrays(minimumCapacity); 374 if (mSize > 0) { 375 System.arraycopy(ohashes, 0, mHashes, 0, mSize); 376 System.arraycopy(oarray, 0, mArray, 0, mSize); 377 } 378 freeArrays(ohashes, oarray, mSize); 379 } 380 if (mSize != oSize) { 381 throw new ConcurrentModificationException(); 382 } 383 } 384 385 /** 386 * Check whether a value exists in the set. 387 * 388 * @param key The value to search for. 389 * @return Returns true if the value exists, else false. 390 */ 391 @Override contains(Object key)392 public boolean contains(Object key) { 393 return indexOf(key) >= 0; 394 } 395 396 /** 397 * Returns the index of a value in the set. 398 * 399 * @param key The value to search for. 400 * @return Returns the index of the value if it exists, else a negative integer. 401 */ indexOf(Object key)402 public int indexOf(Object key) { 403 return key == null ? indexOfNull() 404 : indexOf(key, mIdentityHashCode ? System.identityHashCode(key) : key.hashCode()); 405 } 406 407 /** 408 * Return the value at the given index in the array. 409 * 410 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 411 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 412 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 413 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 414 * 415 * @param index The desired index, must be between 0 and {@link #size()}-1. 416 * @return Returns the value stored at the given index. 417 */ valueAt(int index)418 public E valueAt(int index) { 419 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 420 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 421 // Check if exception should be thrown outside of the critical path. 422 throw new ArrayIndexOutOfBoundsException(index); 423 } 424 return valueAtUnchecked(index); 425 } 426 427 /** 428 * Returns the value at the given index in the array without checking that the index is within 429 * bounds. This allows testing values at the end of the internal array, outside of the 430 * [0, mSize) bounds. 431 * 432 * @hide 433 */ 434 @TestApi valueAtUnchecked(int index)435 public E valueAtUnchecked(int index) { 436 return (E) mArray[index]; 437 } 438 439 /** 440 * Return true if the array map contains no items. 441 */ 442 @Override isEmpty()443 public boolean isEmpty() { 444 return mSize <= 0; 445 } 446 447 /** 448 * Adds the specified object to this set. The set is not modified if it 449 * already contains the object. 450 * 451 * @param value the object to add. 452 * @return {@code true} if this set is modified, {@code false} otherwise. 453 */ 454 @Override add(E value)455 public boolean add(E value) { 456 final int oSize = mSize; 457 final int hash; 458 int index; 459 if (value == null) { 460 hash = 0; 461 index = indexOfNull(); 462 } else { 463 hash = mIdentityHashCode ? System.identityHashCode(value) : value.hashCode(); 464 index = indexOf(value, hash); 465 } 466 if (index >= 0) { 467 return false; 468 } 469 470 index = ~index; 471 if (oSize >= mHashes.length) { 472 final int n = oSize >= (BASE_SIZE * 2) ? (oSize + (oSize >> 1)) 473 : (oSize >= BASE_SIZE ? (BASE_SIZE * 2) : BASE_SIZE); 474 475 if (DEBUG) Log.d(TAG, "add: grow from " + mHashes.length + " to " + n); 476 477 final int[] ohashes = mHashes; 478 final Object[] oarray = mArray; 479 allocArrays(n); 480 481 if (oSize != mSize) { 482 throw new ConcurrentModificationException(); 483 } 484 485 if (mHashes.length > 0) { 486 if (DEBUG) Log.d(TAG, "add: copy 0-" + oSize + " to 0"); 487 System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length); 488 System.arraycopy(oarray, 0, mArray, 0, oarray.length); 489 } 490 491 freeArrays(ohashes, oarray, oSize); 492 } 493 494 if (index < oSize) { 495 if (DEBUG) { 496 Log.d(TAG, "add: move " + index + "-" + (oSize - index) + " to " + (index + 1)); 497 } 498 System.arraycopy(mHashes, index, mHashes, index + 1, oSize - index); 499 System.arraycopy(mArray, index, mArray, index + 1, oSize - index); 500 } 501 502 if (oSize != mSize || index >= mHashes.length) { 503 throw new ConcurrentModificationException(); 504 } 505 506 mHashes[index] = hash; 507 mArray[index] = value; 508 mSize++; 509 return true; 510 } 511 512 /** 513 * Special fast path for appending items to the end of the array without validation. 514 * The array must already be large enough to contain the item. 515 * @hide 516 */ append(E value)517 public void append(E value) { 518 final int oSize = mSize; 519 final int index = mSize; 520 final int hash = value == null ? 0 521 : (mIdentityHashCode ? System.identityHashCode(value) : value.hashCode()); 522 if (index >= mHashes.length) { 523 throw new IllegalStateException("Array is full"); 524 } 525 if (index > 0 && mHashes[index - 1] > hash) { 526 // Cannot optimize since it would break the sorted order - fallback to add() 527 if (DEBUG) { 528 RuntimeException e = new RuntimeException("here"); 529 Log.w(TAG, "New hash " + hash 530 + " is before end of array hash " + mHashes[index - 1] 531 + " at index " + index, e); 532 } 533 add(value); 534 return; 535 } 536 537 if (oSize != mSize) { 538 throw new ConcurrentModificationException(); 539 } 540 541 mSize = index + 1; 542 mHashes[index] = hash; 543 mArray[index] = value; 544 } 545 546 /** 547 * Perform a {@link #add(Object)} of all values in <var>array</var> 548 * @param array The array whose contents are to be retrieved. 549 */ addAll(ArraySet<? extends E> array)550 public void addAll(ArraySet<? extends E> array) { 551 final int N = array.mSize; 552 ensureCapacity(mSize + N); 553 if (mSize == 0) { 554 if (N > 0) { 555 System.arraycopy(array.mHashes, 0, mHashes, 0, N); 556 System.arraycopy(array.mArray, 0, mArray, 0, N); 557 if (0 != mSize) { 558 throw new ConcurrentModificationException(); 559 } 560 mSize = N; 561 } 562 } else { 563 for (int i = 0; i < N; i++) { 564 add(array.valueAt(i)); 565 } 566 } 567 } 568 569 /** 570 * Removes the specified object from this set. 571 * 572 * @param object the object to remove. 573 * @return {@code true} if this set was modified, {@code false} otherwise. 574 */ 575 @Override remove(Object object)576 public boolean remove(Object object) { 577 final int index = indexOf(object); 578 if (index >= 0) { 579 removeAt(index); 580 return true; 581 } 582 return false; 583 } 584 585 /** Returns true if the array size should be decreased. */ shouldShrink()586 private boolean shouldShrink() { 587 return mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3; 588 } 589 590 /** 591 * Returns the new size the array should have. Is only valid if {@link #shouldShrink} returns 592 * true. 593 */ getNewShrunkenSize()594 private int getNewShrunkenSize() { 595 // We don't allow it to shrink smaller than (BASE_SIZE*2) to avoid flapping between that 596 // and BASE_SIZE. 597 return mSize > (BASE_SIZE * 2) ? (mSize + (mSize >> 1)) : (BASE_SIZE * 2); 598 } 599 600 /** 601 * Remove the key/value mapping at the given index. 602 * 603 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 604 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 605 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 606 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 607 * 608 * @param index The desired index, must be between 0 and {@link #size()}-1. 609 * @return Returns the value that was stored at this index. 610 */ removeAt(int index)611 public E removeAt(int index) { 612 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 613 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 614 // Check if exception should be thrown outside of the critical path. 615 throw new ArrayIndexOutOfBoundsException(index); 616 } 617 final int oSize = mSize; 618 final Object old = mArray[index]; 619 if (oSize <= 1) { 620 // Now empty. 621 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0"); 622 clear(); 623 } else { 624 final int nSize = oSize - 1; 625 if (shouldShrink()) { 626 // Shrunk enough to reduce size of arrays. 627 final int n = getNewShrunkenSize(); 628 629 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n); 630 631 final int[] ohashes = mHashes; 632 final Object[] oarray = mArray; 633 allocArrays(n); 634 635 if (index > 0) { 636 if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0"); 637 System.arraycopy(ohashes, 0, mHashes, 0, index); 638 System.arraycopy(oarray, 0, mArray, 0, index); 639 } 640 if (index < nSize) { 641 if (DEBUG) { 642 Log.d(TAG, "remove: copy from " + (index + 1) + "-" + nSize 643 + " to " + index); 644 } 645 System.arraycopy(ohashes, index + 1, mHashes, index, nSize - index); 646 System.arraycopy(oarray, index + 1, mArray, index, nSize - index); 647 } 648 } else { 649 if (index < nSize) { 650 if (DEBUG) { 651 Log.d(TAG, "remove: move " + (index + 1) + "-" + nSize + " to " + index); 652 } 653 System.arraycopy(mHashes, index + 1, mHashes, index, nSize - index); 654 System.arraycopy(mArray, index + 1, mArray, index, nSize - index); 655 } 656 mArray[nSize] = null; 657 } 658 if (oSize != mSize) { 659 throw new ConcurrentModificationException(); 660 } 661 mSize = nSize; 662 } 663 return (E) old; 664 } 665 666 /** 667 * Perform a {@link #remove(Object)} of all values in <var>array</var> 668 * @param array The array whose contents are to be removed. 669 */ removeAll(ArraySet<? extends E> array)670 public boolean removeAll(ArraySet<? extends E> array) { 671 // TODO: If array is sufficiently large, a marking approach might be beneficial. In a first 672 // pass, use the property that the sets are sorted by hash to make this linear passes 673 // (except for hash collisions, which means worst case still n*m), then do one 674 // collection pass into a new array. This avoids binary searches and excessive memcpy. 675 final int N = array.mSize; 676 677 // Note: ArraySet does not make thread-safety guarantees. So instead of OR-ing together all 678 // the single results, compare size before and after. 679 final int originalSize = mSize; 680 for (int i = 0; i < N; i++) { 681 remove(array.valueAt(i)); 682 } 683 return originalSize != mSize; 684 } 685 686 /** 687 * Removes all values that satisfy the predicate. This implementation avoids using the 688 * {@link #iterator()}. 689 * 690 * @param filter A predicate which returns true for elements to be removed 691 */ 692 @Override removeIf(Predicate<? super E> filter)693 public boolean removeIf(Predicate<? super E> filter) { 694 if (mSize == 0) { 695 return false; 696 } 697 698 // Intentionally not using removeAt() to avoid unnecessary intermediate resizing. 699 700 int replaceIndex = 0; 701 int numRemoved = 0; 702 for (int i = 0; i < mSize; ++i) { 703 if (filter.test((E) mArray[i])) { 704 numRemoved++; 705 } else { 706 if (replaceIndex != i) { 707 mArray[replaceIndex] = mArray[i]; 708 mHashes[replaceIndex] = mHashes[i]; 709 } 710 replaceIndex++; 711 } 712 } 713 714 if (numRemoved == 0) { 715 return false; 716 } else if (numRemoved == mSize) { 717 clear(); 718 return true; 719 } 720 721 mSize -= numRemoved; 722 if (shouldShrink()) { 723 // Shrunk enough to reduce size of arrays. 724 final int n = getNewShrunkenSize(); 725 final int[] ohashes = mHashes; 726 final Object[] oarray = mArray; 727 allocArrays(n); 728 729 System.arraycopy(ohashes, 0, mHashes, 0, mSize); 730 System.arraycopy(oarray, 0, mArray, 0, mSize); 731 } else { 732 // Null out values at the end of the array. Not doing it in the loop above to avoid 733 // writing twice to the same index or writing unnecessarily if the array would have been 734 // discarded anyway. 735 for (int i = mSize; i < mArray.length; ++i) { 736 mArray[i] = null; 737 } 738 } 739 return true; 740 } 741 742 /** 743 * Return the number of items in this array map. 744 */ 745 @Override size()746 public int size() { 747 return mSize; 748 } 749 750 /** 751 * Performs the given action for all elements in the stored order. This implementation overrides 752 * the default implementation to avoid using the {@link #iterator()}. 753 * 754 * @param action The action to be performed for each element 755 */ 756 @Override forEach(Consumer<? super E> action)757 public void forEach(Consumer<? super E> action) { 758 if (action == null) { 759 throw new NullPointerException("action must not be null"); 760 } 761 762 for (int i = 0; i < mSize; ++i) { 763 action.accept(valueAt(i)); 764 } 765 } 766 767 @Override toArray()768 public Object[] toArray() { 769 Object[] result = new Object[mSize]; 770 System.arraycopy(mArray, 0, result, 0, mSize); 771 return result; 772 } 773 774 @Override toArray(T[] array)775 public <T> T[] toArray(T[] array) { 776 if (array.length < mSize) { 777 @SuppressWarnings("unchecked") T[] newArray = 778 (T[]) Array.newInstance(array.getClass().getComponentType(), mSize); 779 array = newArray; 780 } 781 System.arraycopy(mArray, 0, array, 0, mSize); 782 if (array.length > mSize) { 783 array[mSize] = null; 784 } 785 return array; 786 } 787 788 /** 789 * {@inheritDoc} 790 * 791 * <p>This implementation returns false if the object is not a set, or 792 * if the sets have different sizes. Otherwise, for each value in this 793 * set, it checks to make sure the value also exists in the other set. 794 * If any value doesn't exist, the method returns false; otherwise, it 795 * returns true. 796 */ 797 @Override equals(@ullable Object object)798 public boolean equals(@Nullable Object object) { 799 if (this == object) { 800 return true; 801 } 802 if (object instanceof Set) { 803 Set<?> set = (Set<?>) object; 804 if (size() != set.size()) { 805 return false; 806 } 807 808 try { 809 for (int i = 0; i < mSize; i++) { 810 E mine = valueAt(i); 811 if (!set.contains(mine)) { 812 return false; 813 } 814 } 815 } catch (NullPointerException ignored) { 816 return false; 817 } catch (ClassCastException ignored) { 818 return false; 819 } 820 return true; 821 } 822 return false; 823 } 824 825 /** 826 * {@inheritDoc} 827 */ 828 @Override hashCode()829 public int hashCode() { 830 final int[] hashes = mHashes; 831 int result = 0; 832 for (int i = 0, s = mSize; i < s; i++) { 833 result += hashes[i]; 834 } 835 return result; 836 } 837 838 /** 839 * {@inheritDoc} 840 * 841 * <p>This implementation composes a string by iterating over its values. If 842 * this set contains itself as a value, the string "(this Set)" 843 * will appear in its place. 844 */ 845 @Override toString()846 public String toString() { 847 if (isEmpty()) { 848 return "{}"; 849 } 850 851 StringBuilder buffer = new StringBuilder(mSize * 14); 852 buffer.append('{'); 853 for (int i = 0; i < mSize; i++) { 854 if (i > 0) { 855 buffer.append(", "); 856 } 857 Object value = valueAt(i); 858 if (value != this) { 859 buffer.append(value); 860 } else { 861 buffer.append("(this Set)"); 862 } 863 } 864 buffer.append('}'); 865 return buffer.toString(); 866 } 867 868 // ------------------------------------------------------------------------ 869 // Interop with traditional Java containers. Not as efficient as using 870 // specialized collection APIs. 871 // ------------------------------------------------------------------------ 872 getCollection()873 private MapCollections<E, E> getCollection() { 874 if (mCollections == null) { 875 mCollections = new MapCollections<E, E>() { 876 @Override 877 protected int colGetSize() { 878 return mSize; 879 } 880 881 @Override 882 protected Object colGetEntry(int index, int offset) { 883 return mArray[index]; 884 } 885 886 @Override 887 protected int colIndexOfKey(Object key) { 888 return indexOf(key); 889 } 890 891 @Override 892 protected int colIndexOfValue(Object value) { 893 return indexOf(value); 894 } 895 896 @Override 897 protected Map<E, E> colGetMap() { 898 throw new UnsupportedOperationException("not a map"); 899 } 900 901 @Override 902 protected void colPut(E key, E value) { 903 add(key); 904 } 905 906 @Override 907 protected E colSetValue(int index, E value) { 908 throw new UnsupportedOperationException("not a map"); 909 } 910 911 @Override 912 protected void colRemoveAt(int index) { 913 removeAt(index); 914 } 915 916 @Override 917 protected void colClear() { 918 clear(); 919 } 920 }; 921 } 922 return mCollections; 923 } 924 925 /** 926 * Return an {@link java.util.Iterator} over all values in the set. 927 * 928 * <p><b>Note:</b> this is a fairly inefficient way to access the array contents, it 929 * requires generating a number of temporary objects and allocates additional state 930 * information associated with the container that will remain for the life of the container.</p> 931 */ 932 @Override iterator()933 public Iterator<E> iterator() { 934 return getCollection().getKeySet().iterator(); 935 } 936 937 /** 938 * Determine if the array set contains all of the values in the given collection. 939 * @param collection The collection whose contents are to be checked against. 940 * @return Returns true if this array set contains a value for every entry 941 * in <var>collection</var>, else returns false. 942 */ 943 @Override containsAll(Collection<?> collection)944 public boolean containsAll(Collection<?> collection) { 945 Iterator<?> it = collection.iterator(); 946 while (it.hasNext()) { 947 if (!contains(it.next())) { 948 return false; 949 } 950 } 951 return true; 952 } 953 954 /** 955 * Perform an {@link #add(Object)} of all values in <var>collection</var> 956 * @param collection The collection whose contents are to be retrieved. 957 */ 958 @Override addAll(Collection<? extends E> collection)959 public boolean addAll(Collection<? extends E> collection) { 960 ensureCapacity(mSize + collection.size()); 961 boolean added = false; 962 for (E value : collection) { 963 added |= add(value); 964 } 965 return added; 966 } 967 968 /** 969 * Remove all values in the array set that exist in the given collection. 970 * @param collection The collection whose contents are to be used to remove values. 971 * @return Returns true if any values were removed from the array set, else false. 972 */ 973 @Override removeAll(Collection<?> collection)974 public boolean removeAll(Collection<?> collection) { 975 boolean removed = false; 976 for (Object value : collection) { 977 removed |= remove(value); 978 } 979 return removed; 980 } 981 982 /** 983 * Remove all values in the array set that do <b>not</b> exist in the given collection. 984 * @param collection The collection whose contents are to be used to determine which 985 * values to keep. 986 * @return Returns true if any values were removed from the array set, else false. 987 */ 988 @Override retainAll(Collection<?> collection)989 public boolean retainAll(Collection<?> collection) { 990 boolean removed = false; 991 for (int i = mSize - 1; i >= 0; i--) { 992 if (!collection.contains(mArray[i])) { 993 removeAt(i); 994 removed = true; 995 } 996 } 997 return removed; 998 } 999 } 1000