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 e.fillInStackTrace(); 530 Log.w(TAG, "New hash " + hash 531 + " is before end of array hash " + mHashes[index - 1] 532 + " at index " + index, e); 533 } 534 add(value); 535 return; 536 } 537 538 if (oSize != mSize) { 539 throw new ConcurrentModificationException(); 540 } 541 542 mSize = index + 1; 543 mHashes[index] = hash; 544 mArray[index] = value; 545 } 546 547 /** 548 * Perform a {@link #add(Object)} of all values in <var>array</var> 549 * @param array The array whose contents are to be retrieved. 550 */ addAll(ArraySet<? extends E> array)551 public void addAll(ArraySet<? extends E> array) { 552 final int N = array.mSize; 553 ensureCapacity(mSize + N); 554 if (mSize == 0) { 555 if (N > 0) { 556 System.arraycopy(array.mHashes, 0, mHashes, 0, N); 557 System.arraycopy(array.mArray, 0, mArray, 0, N); 558 if (0 != mSize) { 559 throw new ConcurrentModificationException(); 560 } 561 mSize = N; 562 } 563 } else { 564 for (int i = 0; i < N; i++) { 565 add(array.valueAt(i)); 566 } 567 } 568 } 569 570 /** 571 * Removes the specified object from this set. 572 * 573 * @param object the object to remove. 574 * @return {@code true} if this set was modified, {@code false} otherwise. 575 */ 576 @Override remove(Object object)577 public boolean remove(Object object) { 578 final int index = indexOf(object); 579 if (index >= 0) { 580 removeAt(index); 581 return true; 582 } 583 return false; 584 } 585 586 /** Returns true if the array size should be decreased. */ shouldShrink()587 private boolean shouldShrink() { 588 return mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3; 589 } 590 591 /** 592 * Returns the new size the array should have. Is only valid if {@link #shouldShrink} returns 593 * true. 594 */ getNewShrunkenSize()595 private int getNewShrunkenSize() { 596 // We don't allow it to shrink smaller than (BASE_SIZE*2) to avoid flapping between that 597 // and BASE_SIZE. 598 return mSize > (BASE_SIZE * 2) ? (mSize + (mSize >> 1)) : (BASE_SIZE * 2); 599 } 600 601 /** 602 * Remove the key/value mapping at the given index. 603 * 604 * <p>For indices outside of the range <code>0...size()-1</code>, the behavior is undefined for 605 * apps targeting {@link android.os.Build.VERSION_CODES#P} and earlier, and an 606 * {@link ArrayIndexOutOfBoundsException} is thrown for apps targeting 607 * {@link android.os.Build.VERSION_CODES#Q} and later.</p> 608 * 609 * @param index The desired index, must be between 0 and {@link #size()}-1. 610 * @return Returns the value that was stored at this index. 611 */ removeAt(int index)612 public E removeAt(int index) { 613 if (index >= mSize && UtilConfig.sThrowExceptionForUpperArrayOutOfBounds) { 614 // The array might be slightly bigger than mSize, in which case, indexing won't fail. 615 // Check if exception should be thrown outside of the critical path. 616 throw new ArrayIndexOutOfBoundsException(index); 617 } 618 final int oSize = mSize; 619 final Object old = mArray[index]; 620 if (oSize <= 1) { 621 // Now empty. 622 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0"); 623 clear(); 624 } else { 625 final int nSize = oSize - 1; 626 if (shouldShrink()) { 627 // Shrunk enough to reduce size of arrays. 628 final int n = getNewShrunkenSize(); 629 630 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n); 631 632 final int[] ohashes = mHashes; 633 final Object[] oarray = mArray; 634 allocArrays(n); 635 636 if (index > 0) { 637 if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0"); 638 System.arraycopy(ohashes, 0, mHashes, 0, index); 639 System.arraycopy(oarray, 0, mArray, 0, index); 640 } 641 if (index < nSize) { 642 if (DEBUG) { 643 Log.d(TAG, "remove: copy from " + (index + 1) + "-" + nSize 644 + " to " + index); 645 } 646 System.arraycopy(ohashes, index + 1, mHashes, index, nSize - index); 647 System.arraycopy(oarray, index + 1, mArray, index, nSize - index); 648 } 649 } else { 650 if (index < nSize) { 651 if (DEBUG) { 652 Log.d(TAG, "remove: move " + (index + 1) + "-" + nSize + " to " + index); 653 } 654 System.arraycopy(mHashes, index + 1, mHashes, index, nSize - index); 655 System.arraycopy(mArray, index + 1, mArray, index, nSize - index); 656 } 657 mArray[nSize] = null; 658 } 659 if (oSize != mSize) { 660 throw new ConcurrentModificationException(); 661 } 662 mSize = nSize; 663 } 664 return (E) old; 665 } 666 667 /** 668 * Perform a {@link #remove(Object)} of all values in <var>array</var> 669 * @param array The array whose contents are to be removed. 670 */ removeAll(ArraySet<? extends E> array)671 public boolean removeAll(ArraySet<? extends E> array) { 672 // TODO: If array is sufficiently large, a marking approach might be beneficial. In a first 673 // pass, use the property that the sets are sorted by hash to make this linear passes 674 // (except for hash collisions, which means worst case still n*m), then do one 675 // collection pass into a new array. This avoids binary searches and excessive memcpy. 676 final int N = array.mSize; 677 678 // Note: ArraySet does not make thread-safety guarantees. So instead of OR-ing together all 679 // the single results, compare size before and after. 680 final int originalSize = mSize; 681 for (int i = 0; i < N; i++) { 682 remove(array.valueAt(i)); 683 } 684 return originalSize != mSize; 685 } 686 687 /** 688 * Removes all values that satisfy the predicate. This implementation avoids using the 689 * {@link #iterator()}. 690 * 691 * @param filter A predicate which returns true for elements to be removed 692 */ 693 @Override removeIf(Predicate<? super E> filter)694 public boolean removeIf(Predicate<? super E> filter) { 695 if (mSize == 0) { 696 return false; 697 } 698 699 // Intentionally not using removeAt() to avoid unnecessary intermediate resizing. 700 701 int replaceIndex = 0; 702 int numRemoved = 0; 703 for (int i = 0; i < mSize; ++i) { 704 if (filter.test((E) mArray[i])) { 705 numRemoved++; 706 } else { 707 if (replaceIndex != i) { 708 mArray[replaceIndex] = mArray[i]; 709 mHashes[replaceIndex] = mHashes[i]; 710 } 711 replaceIndex++; 712 } 713 } 714 715 if (numRemoved == 0) { 716 return false; 717 } else if (numRemoved == mSize) { 718 clear(); 719 return true; 720 } 721 722 mSize -= numRemoved; 723 if (shouldShrink()) { 724 // Shrunk enough to reduce size of arrays. 725 final int n = getNewShrunkenSize(); 726 final int[] ohashes = mHashes; 727 final Object[] oarray = mArray; 728 allocArrays(n); 729 730 System.arraycopy(ohashes, 0, mHashes, 0, mSize); 731 System.arraycopy(oarray, 0, mArray, 0, mSize); 732 } else { 733 // Null out values at the end of the array. Not doing it in the loop above to avoid 734 // writing twice to the same index or writing unnecessarily if the array would have been 735 // discarded anyway. 736 for (int i = mSize; i < mArray.length; ++i) { 737 mArray[i] = null; 738 } 739 } 740 return true; 741 } 742 743 /** 744 * Return the number of items in this array map. 745 */ 746 @Override size()747 public int size() { 748 return mSize; 749 } 750 751 /** 752 * Performs the given action for all elements in the stored order. This implementation overrides 753 * the default implementation to avoid using the {@link #iterator()}. 754 * 755 * @param action The action to be performed for each element 756 */ 757 @Override forEach(Consumer<? super E> action)758 public void forEach(Consumer<? super E> action) { 759 if (action == null) { 760 throw new NullPointerException("action must not be null"); 761 } 762 763 for (int i = 0; i < mSize; ++i) { 764 action.accept(valueAt(i)); 765 } 766 } 767 768 @Override toArray()769 public Object[] toArray() { 770 Object[] result = new Object[mSize]; 771 System.arraycopy(mArray, 0, result, 0, mSize); 772 return result; 773 } 774 775 @Override toArray(T[] array)776 public <T> T[] toArray(T[] array) { 777 if (array.length < mSize) { 778 @SuppressWarnings("unchecked") T[] newArray = 779 (T[]) Array.newInstance(array.getClass().getComponentType(), mSize); 780 array = newArray; 781 } 782 System.arraycopy(mArray, 0, array, 0, mSize); 783 if (array.length > mSize) { 784 array[mSize] = null; 785 } 786 return array; 787 } 788 789 /** 790 * {@inheritDoc} 791 * 792 * <p>This implementation returns false if the object is not a set, or 793 * if the sets have different sizes. Otherwise, for each value in this 794 * set, it checks to make sure the value also exists in the other set. 795 * If any value doesn't exist, the method returns false; otherwise, it 796 * returns true. 797 */ 798 @Override equals(@ullable Object object)799 public boolean equals(@Nullable Object object) { 800 if (this == object) { 801 return true; 802 } 803 if (object instanceof Set) { 804 Set<?> set = (Set<?>) object; 805 if (size() != set.size()) { 806 return false; 807 } 808 809 try { 810 for (int i = 0; i < mSize; i++) { 811 E mine = valueAt(i); 812 if (!set.contains(mine)) { 813 return false; 814 } 815 } 816 } catch (NullPointerException ignored) { 817 return false; 818 } catch (ClassCastException ignored) { 819 return false; 820 } 821 return true; 822 } 823 return false; 824 } 825 826 /** 827 * {@inheritDoc} 828 */ 829 @Override hashCode()830 public int hashCode() { 831 final int[] hashes = mHashes; 832 int result = 0; 833 for (int i = 0, s = mSize; i < s; i++) { 834 result += hashes[i]; 835 } 836 return result; 837 } 838 839 /** 840 * {@inheritDoc} 841 * 842 * <p>This implementation composes a string by iterating over its values. If 843 * this set contains itself as a value, the string "(this Set)" 844 * will appear in its place. 845 */ 846 @Override toString()847 public String toString() { 848 if (isEmpty()) { 849 return "{}"; 850 } 851 852 StringBuilder buffer = new StringBuilder(mSize * 14); 853 buffer.append('{'); 854 for (int i = 0; i < mSize; i++) { 855 if (i > 0) { 856 buffer.append(", "); 857 } 858 Object value = valueAt(i); 859 if (value != this) { 860 buffer.append(value); 861 } else { 862 buffer.append("(this Set)"); 863 } 864 } 865 buffer.append('}'); 866 return buffer.toString(); 867 } 868 869 // ------------------------------------------------------------------------ 870 // Interop with traditional Java containers. Not as efficient as using 871 // specialized collection APIs. 872 // ------------------------------------------------------------------------ 873 getCollection()874 private MapCollections<E, E> getCollection() { 875 if (mCollections == null) { 876 mCollections = new MapCollections<E, E>() { 877 @Override 878 protected int colGetSize() { 879 return mSize; 880 } 881 882 @Override 883 protected Object colGetEntry(int index, int offset) { 884 return mArray[index]; 885 } 886 887 @Override 888 protected int colIndexOfKey(Object key) { 889 return indexOf(key); 890 } 891 892 @Override 893 protected int colIndexOfValue(Object value) { 894 return indexOf(value); 895 } 896 897 @Override 898 protected Map<E, E> colGetMap() { 899 throw new UnsupportedOperationException("not a map"); 900 } 901 902 @Override 903 protected void colPut(E key, E value) { 904 add(key); 905 } 906 907 @Override 908 protected E colSetValue(int index, E value) { 909 throw new UnsupportedOperationException("not a map"); 910 } 911 912 @Override 913 protected void colRemoveAt(int index) { 914 removeAt(index); 915 } 916 917 @Override 918 protected void colClear() { 919 clear(); 920 } 921 }; 922 } 923 return mCollections; 924 } 925 926 /** 927 * Return an {@link java.util.Iterator} over all values in the set. 928 * 929 * <p><b>Note:</b> this is a fairly inefficient way to access the array contents, it 930 * requires generating a number of temporary objects and allocates additional state 931 * information associated with the container that will remain for the life of the container.</p> 932 */ 933 @Override iterator()934 public Iterator<E> iterator() { 935 return getCollection().getKeySet().iterator(); 936 } 937 938 /** 939 * Determine if the array set contains all of the values in the given collection. 940 * @param collection The collection whose contents are to be checked against. 941 * @return Returns true if this array set contains a value for every entry 942 * in <var>collection</var>, else returns false. 943 */ 944 @Override containsAll(Collection<?> collection)945 public boolean containsAll(Collection<?> collection) { 946 Iterator<?> it = collection.iterator(); 947 while (it.hasNext()) { 948 if (!contains(it.next())) { 949 return false; 950 } 951 } 952 return true; 953 } 954 955 /** 956 * Perform an {@link #add(Object)} of all values in <var>collection</var> 957 * @param collection The collection whose contents are to be retrieved. 958 */ 959 @Override addAll(Collection<? extends E> collection)960 public boolean addAll(Collection<? extends E> collection) { 961 ensureCapacity(mSize + collection.size()); 962 boolean added = false; 963 for (E value : collection) { 964 added |= add(value); 965 } 966 return added; 967 } 968 969 /** 970 * Remove all values in the array set that exist in the given collection. 971 * @param collection The collection whose contents are to be used to remove values. 972 * @return Returns true if any values were removed from the array set, else false. 973 */ 974 @Override removeAll(Collection<?> collection)975 public boolean removeAll(Collection<?> collection) { 976 boolean removed = false; 977 for (Object value : collection) { 978 removed |= remove(value); 979 } 980 return removed; 981 } 982 983 /** 984 * Remove all values in the array set that do <b>not</b> exist in the given collection. 985 * @param collection The collection whose contents are to be used to determine which 986 * values to keep. 987 * @return Returns true if any values were removed from the array set, else false. 988 */ 989 @Override retainAll(Collection<?> collection)990 public boolean retainAll(Collection<?> collection) { 991 boolean removed = false; 992 for (int i = mSize - 1; i >= 0; i--) { 993 if (!collection.contains(mArray[i])) { 994 removeAt(i); 995 removed = true; 996 } 997 } 998 return removed; 999 } 1000 } 1001