001/* 002 * Copyright (C) 2017 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtCompatible; 021import com.google.common.base.Preconditions; 022import com.google.errorprone.annotations.CanIgnoreReturnValue; 023import java.io.Serializable; 024import java.util.AbstractList; 025import java.util.Arrays; 026import java.util.Collection; 027import java.util.List; 028import java.util.RandomAccess; 029import javax.annotation.CheckReturnValue; 030import javax.annotation.Nullable; 031 032/** 033 * An immutable array of {@code int} values, with an API resembling {@link List}. 034 * 035 * <p>Advantages compared to {@code int[]}: 036 * 037 * <ul> 038 * <li>All the many well-known advantages of immutability (read <i>Effective Java</i>, second 039 * edition, Item 15). 040 * <li>Has the value-based (not identity-based) {@link #equals}, {@link #hashCode}, and 041 * {@link #toString} behavior you expect 042 * <li>Offers useful operations beyond just {@code get} and {@code length}, so you don't have to 043 * hunt through classes like {@link Arrays} and {@link Ints} for them. 044 * <li>Supports a copy-free {@link #subArray} view, so methods that accept this type don't need to 045 * add overloads that accept start and end indexes. 046 * <li>Access to all collection-based utilities via {@link #asList} (though at the cost of 047 * allocating garbage). 048 * </ul> 049 * 050 * <p>Disadvantages compared to {@code int[]}: 051 * 052 * <ul> 053 * <li>Memory footprint has a fixed overhead (about 24 bytes per instance). 054 * <li><i>Some</i> construction use cases force the data to be copied (though several construction 055 * APIs are offered that don't). 056 * <li>Can't be passed directly to methods that expect {@code int[]} (though the most common 057 * utilities do have replacements here). 058 * <li>Dependency on {@code com.google.common} / Guava. 059 * </ul> 060 * 061 * <p>Advantages compared to {@link com.google.common.collect.ImmutableList ImmutableList}{@code 062 * <Integer>}: 063 * 064 * <ul> 065 * <li>Improved memory compactness and locality 066 * <li>Can be queried without allocating garbage 067 * </ul> 068 * 069 * <p>Disadvantages compared to {@code ImmutableList<Integer>}: 070 * 071 * <ul> 072 * <li>Can't be passed directly to methods that expect {@code Iterable}, {@code Collection}, or 073 * {@code List} (though the most common utilities do have replacements here, and there is a 074 * lazy {@link #asList} view). 075 * </ul> 076 * 077 * @since 22.0 078 */ 079@Beta 080@GwtCompatible 081public final class ImmutableIntArray implements Serializable { 082 private static final ImmutableIntArray EMPTY = new ImmutableIntArray(new int[0]); 083 084 /** Returns the empty array. */ 085 public static ImmutableIntArray of() { 086 return EMPTY; 087 } 088 089 /** Returns an immutable array containing a single value. */ 090 public static ImmutableIntArray of(int e0) { 091 return new ImmutableIntArray(new int[] {e0}); 092 } 093 094 /** Returns an immutable array containing the given values, in order. */ 095 public static ImmutableIntArray of(int e0, int e1) { 096 return new ImmutableIntArray(new int[] {e0, e1}); 097 } 098 099 /** Returns an immutable array containing the given values, in order. */ 100 public static ImmutableIntArray of(int e0, int e1, int e2) { 101 return new ImmutableIntArray(new int[] {e0, e1, e2}); 102 } 103 104 /** Returns an immutable array containing the given values, in order. */ 105 public static ImmutableIntArray of(int e0, int e1, int e2, int e3) { 106 return new ImmutableIntArray(new int[] {e0, e1, e2, e3}); 107 } 108 109 /** Returns an immutable array containing the given values, in order. */ 110 public static ImmutableIntArray of(int e0, int e1, int e2, int e3, int e4) { 111 return new ImmutableIntArray(new int[] {e0, e1, e2, e3, e4}); 112 } 113 114 /** Returns an immutable array containing the given values, in order. */ 115 public static ImmutableIntArray of(int e0, int e1, int e2, int e3, int e4, int e5) { 116 return new ImmutableIntArray(new int[] {e0, e1, e2, e3, e4, e5}); 117 } 118 119 // TODO(kevinb): go up to 11? 120 121 /** Returns an immutable array containing the given values, in order. */ 122 // Use (first, rest) so that `of(someIntArray)` won't compile (they should use copyOf), which is 123 // okay since we have to copy the just-created array anyway. 124 public static ImmutableIntArray of(int first, int... rest) { 125 int[] array = new int[rest.length + 1]; 126 array[0] = first; 127 System.arraycopy(rest, 0, array, 1, rest.length); 128 return new ImmutableIntArray(array); 129 } 130 131 /** Returns an immutable array containing the given values, in order. */ 132 public static ImmutableIntArray copyOf(int[] values) { 133 return values.length == 0 ? EMPTY : new ImmutableIntArray(Arrays.copyOf(values, values.length)); 134 } 135 136 /** Returns an immutable array containing the given values, in order. */ 137 public static ImmutableIntArray copyOf(Collection<Integer> values) { 138 return values.isEmpty() ? EMPTY : new ImmutableIntArray(Ints.toArray(values)); 139 } 140 141 /** 142 * Returns an immutable array containing the given values, in order. 143 * 144 * <p><b>Performance note:</b> this method delegates to {@link #copyOf(Collection)} if {@code 145 * values} is a {@link Collection}. Otherwise it creates a {@link #builder} and uses {@link 146 * Builder#addAll(Iterable)}, with all the performance implications associated with that. 147 */ 148 public static ImmutableIntArray copyOf(Iterable<Integer> values) { 149 if (values instanceof Collection) { 150 return copyOf((Collection<Integer>) values); 151 } 152 return builder().addAll(values).build(); 153 } 154 155 /** 156 * Returns a new, empty builder for {@link ImmutableIntArray} instances, sized to hold up to 157 * {@code initialCapacity} values without resizing. The returned builder is not thread-safe. 158 * 159 * <p><b>Performance note:</b> When feasible, {@code initialCapacity} should be the exact number 160 * of values that will be added, if that knowledge is readily available. It is better to guess a 161 * value slightly too high than slightly too low. If the value is not exact, the {@link 162 * ImmutableIntArray} that is built will very likely occupy more memory than strictly necessary; 163 * to trim memory usage, build using {@code builder.build().trimmed()}. 164 */ 165 public static Builder builder(int initialCapacity) { 166 checkArgument(initialCapacity >= 0, "Invalid initialCapacity: %s", initialCapacity); 167 return new Builder(initialCapacity); 168 } 169 170 /** 171 * Returns a new, empty builder for {@link ImmutableIntArray} instances, with a default initial 172 * capacity. The returned builder is not thread-safe. 173 * 174 * <p><b>Performance note:</b> The {@link ImmutableIntArray} that is built will very likely occupy 175 * more memory than necessary; to trim memory usage, build using {@code 176 * builder.build().trimmed()}. 177 */ 178 public static Builder builder() { 179 return new Builder(10); 180 } 181 182 /** 183 * A builder for {@link ImmutableIntArray} instances; obtained using {@link 184 * ImmutableIntArray#builder}. 185 */ 186 @CanIgnoreReturnValue 187 public static final class Builder { 188 private int[] array; 189 private int count = 0; // <= array.length 190 191 Builder(int initialCapacity) { 192 array = new int[initialCapacity]; 193 } 194 195 /** 196 * Appends {@code value} to the end of the values the built {@link ImmutableIntArray} will 197 * contain. 198 */ 199 public Builder add(int value) { 200 ensureRoomFor(1); 201 array[count] = value; 202 count += 1; 203 return this; 204 } 205 206 /** 207 * Appends {@code values}, in order, to the end of the values the built {@link 208 * ImmutableIntArray} will contain. 209 */ 210 public Builder addAll(int[] values) { 211 ensureRoomFor(values.length); 212 System.arraycopy(values, 0, array, count, values.length); 213 count += values.length; 214 return this; 215 } 216 217 /** 218 * Appends {@code values}, in order, to the end of the values the built {@link 219 * ImmutableIntArray} will contain. 220 */ 221 public Builder addAll(Iterable<Integer> values) { 222 if (values instanceof Collection) { 223 return addAll((Collection<Integer>) values); 224 } 225 for (Integer value : values) { 226 add(value); 227 } 228 return this; 229 } 230 231 /** 232 * Appends {@code values}, in order, to the end of the values the built {@link 233 * ImmutableIntArray} will contain. 234 */ 235 public Builder addAll(Collection<Integer> values) { 236 ensureRoomFor(values.size()); 237 for (Integer value : values) { 238 array[count++] = value; 239 } 240 return this; 241 } 242 243 /** 244 * Appends {@code values}, in order, to the end of the values the built {@link 245 * ImmutableIntArray} will contain. 246 */ 247 public Builder addAll(ImmutableIntArray values) { 248 ensureRoomFor(values.length()); 249 System.arraycopy(values.array, values.start, array, count, values.length()); 250 count += values.length(); 251 return this; 252 } 253 254 private void ensureRoomFor(int numberToAdd) { 255 int newCount = count + numberToAdd; // TODO(kevinb): check overflow now? 256 if (newCount > array.length) { 257 int[] newArray = new int[expandedCapacity(array.length, newCount)]; 258 System.arraycopy(array, 0, newArray, 0, count); 259 this.array = newArray; 260 } 261 } 262 263 // Unfortunately this is pasted from ImmutableCollection.Builder. 264 private static int expandedCapacity(int oldCapacity, int minCapacity) { 265 if (minCapacity < 0) { 266 throw new AssertionError("cannot store more than MAX_VALUE elements"); 267 } 268 // careful of overflow! 269 int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; 270 if (newCapacity < minCapacity) { 271 newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; 272 } 273 if (newCapacity < 0) { 274 newCapacity = Integer.MAX_VALUE; // guaranteed to be >= newCapacity 275 } 276 return newCapacity; 277 } 278 279 /** 280 * Returns a new immutable array. The builder can continue to be used after this call, to 281 * append more values and build again. 282 * 283 * <p><b>Performance note:</b> the returned array is backed by the same array as the builder, so 284 * no data is copied as part of this step, but this may occupy more memory than strictly 285 * necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}. 286 */ 287 @CheckReturnValue 288 public ImmutableIntArray build() { 289 return count == 0 ? EMPTY : new ImmutableIntArray(array, 0, count); 290 } 291 } 292 293 // Instance stuff here 294 295 private final int[] array; 296 297 /* 298 * TODO(kevinb): evaluate the trade-offs of going bimorphic to save these two fields from most 299 * instances. Note that the instances that would get smaller are the right set to care about 300 * optimizing, because the rest have the option of calling `trimmed`. 301 */ 302 303 private final transient int start; // it happens that we only serialize instances where this is 0 304 private final int end; // exclusive 305 306 private ImmutableIntArray(int[] array) { 307 this(array, 0, array.length); 308 } 309 310 private ImmutableIntArray(int[] array, int start, int end) { 311 this.array = array; 312 this.start = start; 313 this.end = end; 314 } 315 316 /** Returns the number of values in this array. */ 317 public int length() { 318 return end - start; 319 } 320 321 /** Returns {@code true} if there are no values in this array ({@link #length} is zero). */ 322 public boolean isEmpty() { 323 return end == start; 324 } 325 326 /** 327 * Returns the {@code int} value present at the given index. 328 * 329 * @throws IndexOutOfBoundsException if {@code index} is negative, or greater than or equal to 330 * {@link #length} 331 */ 332 public int get(int index) { 333 Preconditions.checkElementIndex(index, length()); 334 return array[start + index]; 335 } 336 337 /** 338 * Returns the smallest index for which {@link #get} returns {@code target}, or {@code -1} if no 339 * such index exists. Equivalent to {@code asList().indexOf(target)}. 340 */ 341 public int indexOf(int target) { 342 for (int i = start; i < end; i++) { 343 if (array[i] == target) { 344 return i - start; 345 } 346 } 347 return -1; 348 } 349 350 /** 351 * Returns the largest index for which {@link #get} returns {@code target}, or {@code -1} if no 352 * such index exists. Equivalent to {@code asList().lastIndexOf(target)}. 353 */ 354 public int lastIndexOf(int target) { 355 for (int i = end - 1; i >= start; i--) { 356 if (array[i] == target) { 357 return i - start; 358 } 359 } 360 return -1; 361 } 362 363 /** 364 * Returns {@code true} if {@code target} is present at any index in this array. Equivalent to 365 * {@code asList().contains(target)}. 366 */ 367 public boolean contains(int target) { 368 return indexOf(target) >= 0; 369 } 370 371 /** Returns a new, mutable copy of this array's values, as a primitive {@code int[]}. */ 372 public int[] toArray() { 373 return Arrays.copyOfRange(array, start, end); 374 } 375 376 /** 377 * Returns a new immutable array containing the values in the specified range. 378 * 379 * <p><b>Performance note:</b> The returned array has the same full memory footprint as this one 380 * does (no actual copying is performed). To reduce memory usage, use {@code subArray(start, 381 * end).trimmed()}. 382 */ 383 public ImmutableIntArray subArray(int startIndex, int endIndex) { 384 Preconditions.checkPositionIndexes(startIndex, endIndex, length()); 385 return startIndex == endIndex 386 ? EMPTY 387 : new ImmutableIntArray(array, start + startIndex, start + endIndex); 388 } 389 390 /** 391 * Returns an immutable <i>view</i> of this array's values as a {@code List}; note that {@code 392 * int} values are boxed into {@link Integer} instances on demand, which can be very expensive. 393 * The returned list should be used once and discarded. For any usages beyond than that, pass the 394 * returned list to {@link com.google.common.collect.ImmutableList#copyOf(Collection) 395 * ImmutableList.copyOf} and use that list instead. 396 */ 397 public List<Integer> asList() { 398 /* 399 * Typically we cache this kind of thing, but much repeated use of this view is a performance 400 * anti-pattern anyway. If we cache, then everyone pays a price in memory footprint even if 401 * they never use this method. 402 */ 403 return new AsList(this); 404 } 405 406 // TODO(kevinb): Serializable 407 static class AsList extends AbstractList<Integer> implements RandomAccess { 408 private final ImmutableIntArray parent; 409 410 private AsList(ImmutableIntArray parent) { 411 this.parent = parent; 412 } 413 414 // inherit: isEmpty, containsAll, toArray x2, {,list,spl}iterator, stream, forEach, mutations 415 416 @Override 417 public int size() { 418 return parent.length(); 419 } 420 421 @Override 422 public Integer get(int index) { 423 return parent.get(index); 424 } 425 426 @Override 427 public boolean contains(Object target) { 428 return indexOf(target) >= 0; 429 } 430 431 @Override 432 public int indexOf(Object target) { 433 return target instanceof Integer ? parent.indexOf((Integer) target) : -1; 434 } 435 436 @Override 437 public int lastIndexOf(Object target) { 438 return target instanceof Integer ? parent.lastIndexOf((Integer) target) : -1; 439 } 440 441 @Override 442 public List<Integer> subList(int fromIndex, int toIndex) { 443 return parent.subArray(fromIndex, toIndex).asList(); 444 } 445 446 @Override 447 public boolean equals(@Nullable Object object) { 448 if (object instanceof AsList) { 449 AsList that = (AsList) object; 450 return this.parent.equals(that.parent); 451 } 452 // We could delegate to super now but it would still box too much 453 if (!(object instanceof List)) { 454 return false; 455 } 456 List<?> that = (List<?>) object; 457 if (this.size() != that.size()) { 458 return false; 459 } 460 int i = parent.start; 461 // Since `that` is very likely RandomAccess we could avoid allocating this iterator... 462 for (Object element : that) { 463 if (!(element instanceof Integer) || parent.array[i++] != (Integer) element) { 464 return false; 465 } 466 } 467 return true; 468 } 469 470 // Because we happen to use the same formula. If that changes, just don't override this. 471 @Override 472 public int hashCode() { 473 return parent.hashCode(); 474 } 475 476 @Override 477 public String toString() { 478 return parent.toString(); 479 } 480 } 481 482 @Override 483 public boolean equals(@Nullable Object object) { 484 if (object == this) { 485 return true; 486 } 487 if (!(object instanceof ImmutableIntArray)) { 488 return false; 489 } 490 ImmutableIntArray that = (ImmutableIntArray) object; 491 if (this.length() != that.length()) { 492 return false; 493 } 494 for (int i = 0; i < length(); i++) { 495 if (this.get(i) != that.get(i)) { 496 return false; 497 } 498 } 499 return true; 500 } 501 502 /** Returns an unspecified hash code for the contents of this immutable array. */ 503 @Override 504 public int hashCode() { 505 int hash = 1; 506 for (int i = start; i < end; i++) { 507 hash *= 31; 508 hash += Ints.hashCode(array[i]); 509 } 510 return hash; 511 } 512 513 /** 514 * Returns a string representation of this array in the same form as {@link 515 * Arrays#toString(int[])}, for example {@code "[1, 2, 3]"}. 516 */ 517 @Override 518 public String toString() { 519 if (isEmpty()) { 520 return "[]"; 521 } 522 StringBuilder builder = new StringBuilder(length() * 5); // rough estimate is fine 523 builder.append('[').append(array[start]); 524 525 for (int i = start + 1; i < end; i++) { 526 builder.append(", ").append(array[i]); 527 } 528 builder.append(']'); 529 return builder.toString(); 530 } 531 532 /** 533 * Returns an immutable array containing the same values as {@code this} array. This is logically 534 * a no-op, and in some circumstances {@code this} itself is returned. However, if this instance 535 * is a {@link #subArray} view of a larger array, this method will copy only the appropriate range 536 * of values, resulting in an equivalent array with a smaller memory footprint. 537 */ 538 public ImmutableIntArray trimmed() { 539 return isPartialView() ? new ImmutableIntArray(toArray()) : this; 540 } 541 542 private boolean isPartialView() { 543 return start > 0 || end < array.length; 544 } 545 546 Object writeReplace() { 547 return trimmed(); 548 } 549 550 Object readResolve() { 551 return isEmpty() ? EMPTY : this; 552 } 553}