001/* 002 * Copyright (C) 2008 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; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.base.Preconditions.checkPositionIndexes; 021 022import com.google.common.annotations.GwtCompatible; 023import com.google.common.base.Converter; 024import java.io.Serializable; 025import java.util.AbstractList; 026import java.util.Arrays; 027import java.util.Collection; 028import java.util.Collections; 029import java.util.Comparator; 030import java.util.List; 031import java.util.RandomAccess; 032import javax.annotation.CheckForNull; 033 034/** 035 * Static utility methods pertaining to {@code long} primitives, that are not already found in 036 * either {@link Long} or {@link Arrays}. 037 * 038 * <p>See the Guava User Guide article on <a 039 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 040 * 041 * @author Kevin Bourrillion 042 * @since 1.0 043 */ 044@GwtCompatible 045@ElementTypesAreNonnullByDefault 046public final class Longs { 047 private Longs() {} 048 049 /** 050 * The number of bytes required to represent a primitive {@code long} value. 051 * 052 * <p><b>Java 8 users:</b> use {@link Long#BYTES} instead. 053 */ 054 public static final int BYTES = Long.SIZE / Byte.SIZE; 055 056 /** 057 * The largest power of two that can be represented as a {@code long}. 058 * 059 * @since 10.0 060 */ 061 public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); 062 063 /** 064 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Long) 065 * value).hashCode()}. 066 * 067 * <p>This method always return the value specified by {@link Long#hashCode()} in java, which 068 * might be different from {@code ((Long) value).hashCode()} in GWT because {@link 069 * Long#hashCode()} in GWT does not obey the JRE contract. 070 * 071 * <p><b>Java 8 users:</b> use {@link Long#hashCode(long)} instead. 072 * 073 * @param value a primitive {@code long} value 074 * @return a hash code for the value 075 */ 076 public static int hashCode(long value) { 077 return (int) (value ^ (value >>> 32)); 078 } 079 080 /** 081 * Compares the two specified {@code long} values. The sign of the value returned is the same as 082 * that of {@code ((Long) a).compareTo(b)}. 083 * 084 * <p><b>Note for Java 7 and later:</b> this method should be treated as deprecated; use the 085 * equivalent {@link Long#compare} method instead. 086 * 087 * @param a the first {@code long} to compare 088 * @param b the second {@code long} to compare 089 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 090 * greater than {@code b}; or zero if they are equal 091 */ 092 public static int compare(long a, long b) { 093 return (a < b) ? -1 : ((a > b) ? 1 : 0); 094 } 095 096 /** 097 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. 098 * 099 * @param array an array of {@code long} values, possibly empty 100 * @param target a primitive {@code long} value 101 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 102 */ 103 public static boolean contains(long[] array, long target) { 104 for (long value : array) { 105 if (value == target) { 106 return true; 107 } 108 } 109 return false; 110 } 111 112 /** 113 * Returns the index of the first appearance of the value {@code target} in {@code array}. 114 * 115 * @param array an array of {@code long} values, possibly empty 116 * @param target a primitive {@code long} value 117 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 118 * such index exists. 119 */ 120 public static int indexOf(long[] array, long target) { 121 return indexOf(array, target, 0, array.length); 122 } 123 124 // TODO(kevinb): consider making this public 125 private static int indexOf(long[] array, long target, int start, int end) { 126 for (int i = start; i < end; i++) { 127 if (array[i] == target) { 128 return i; 129 } 130 } 131 return -1; 132 } 133 134 /** 135 * Returns the start position of the first occurrence of the specified {@code target} within 136 * {@code array}, or {@code -1} if there is no such occurrence. 137 * 138 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 139 * i, i + target.length)} contains exactly the same elements as {@code target}. 140 * 141 * @param array the array to search for the sequence {@code target} 142 * @param target the array to search for as a sub-sequence of {@code array} 143 */ 144 public static int indexOf(long[] array, long[] target) { 145 checkNotNull(array, "array"); 146 checkNotNull(target, "target"); 147 if (target.length == 0) { 148 return 0; 149 } 150 151 outer: 152 for (int i = 0; i < array.length - target.length + 1; i++) { 153 for (int j = 0; j < target.length; j++) { 154 if (array[i + j] != target[j]) { 155 continue outer; 156 } 157 } 158 return i; 159 } 160 return -1; 161 } 162 163 /** 164 * Returns the index of the last appearance of the value {@code target} in {@code array}. 165 * 166 * @param array an array of {@code long} values, possibly empty 167 * @param target a primitive {@code long} value 168 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 169 * such index exists. 170 */ 171 public static int lastIndexOf(long[] array, long target) { 172 return lastIndexOf(array, target, 0, array.length); 173 } 174 175 // TODO(kevinb): consider making this public 176 private static int lastIndexOf(long[] array, long target, int start, int end) { 177 for (int i = end - 1; i >= start; i--) { 178 if (array[i] == target) { 179 return i; 180 } 181 } 182 return -1; 183 } 184 185 /** 186 * Returns the least value present in {@code array}. 187 * 188 * @param array a <i>nonempty</i> array of {@code long} values 189 * @return the value present in {@code array} that is less than or equal to every other value in 190 * the array 191 * @throws IllegalArgumentException if {@code array} is empty 192 */ 193 public static long min(long... array) { 194 checkArgument(array.length > 0); 195 long min = array[0]; 196 for (int i = 1; i < array.length; i++) { 197 if (array[i] < min) { 198 min = array[i]; 199 } 200 } 201 return min; 202 } 203 204 /** 205 * Returns the greatest value present in {@code array}. 206 * 207 * @param array a <i>nonempty</i> array of {@code long} values 208 * @return the value present in {@code array} that is greater than or equal to every other value 209 * in the array 210 * @throws IllegalArgumentException if {@code array} is empty 211 */ 212 public static long max(long... array) { 213 checkArgument(array.length > 0); 214 long max = array[0]; 215 for (int i = 1; i < array.length; i++) { 216 if (array[i] > max) { 217 max = array[i]; 218 } 219 } 220 return max; 221 } 222 223 /** 224 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 225 * 226 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 227 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 228 * value} is greater than {@code max}, {@code max} is returned. 229 * 230 * @param value the {@code long} value to constrain 231 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 232 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 233 * @throws IllegalArgumentException if {@code min > max} 234 * @since 21.0 235 */ 236 public static long constrainToRange(long value, long min, long max) { 237 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 238 return Math.min(Math.max(value, min), max); 239 } 240 241 /** 242 * Returns the values from each provided array combined into a single array. For example, {@code 243 * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}. 244 * 245 * @param arrays zero or more {@code long} arrays 246 * @return a single array containing all the values from the source arrays, in order 247 */ 248 public static long[] concat(long[]... arrays) { 249 int length = 0; 250 for (long[] array : arrays) { 251 length += array.length; 252 } 253 long[] result = new long[length]; 254 int pos = 0; 255 for (long[] array : arrays) { 256 System.arraycopy(array, 0, result, pos, array.length); 257 pos += array.length; 258 } 259 return result; 260 } 261 262 /** 263 * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to 264 * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code 265 * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 266 * 0x18, 0x19}}. 267 * 268 * <p>If you need to convert and concatenate several values (possibly even of different types), 269 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 270 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 271 */ 272 public static byte[] toByteArray(long value) { 273 // Note that this code needs to stay compatible with GWT, which has known 274 // bugs when narrowing byte casts of long values occur. 275 byte[] result = new byte[8]; 276 for (int i = 7; i >= 0; i--) { 277 result[i] = (byte) (value & 0xffL); 278 value >>= 8; 279 } 280 return result; 281 } 282 283 /** 284 * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes 285 * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the 286 * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the 287 * {@code long} value {@code 0x1213141516171819L}. 288 * 289 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 290 * flexibility at little cost in readability. 291 * 292 * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements 293 */ 294 public static long fromByteArray(byte[] bytes) { 295 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 296 return fromBytes( 297 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); 298 } 299 300 /** 301 * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian 302 * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. 303 * 304 * @since 7.0 305 */ 306 public static long fromBytes( 307 byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { 308 return (b1 & 0xFFL) << 56 309 | (b2 & 0xFFL) << 48 310 | (b3 & 0xFFL) << 40 311 | (b4 & 0xFFL) << 32 312 | (b5 & 0xFFL) << 24 313 | (b6 & 0xFFL) << 16 314 | (b7 & 0xFFL) << 8 315 | (b8 & 0xFFL); 316 } 317 318 /* 319 * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs 320 * class. 321 */ 322 static final class AsciiDigits { 323 private AsciiDigits() {} 324 325 private static final byte[] asciiDigits; 326 327 static { 328 byte[] result = new byte[128]; 329 Arrays.fill(result, (byte) -1); 330 for (int i = 0; i < 10; i++) { 331 result['0' + i] = (byte) i; 332 } 333 for (int i = 0; i < 26; i++) { 334 result['A' + i] = (byte) (10 + i); 335 result['a' + i] = (byte) (10 + i); 336 } 337 asciiDigits = result; 338 } 339 340 static int digit(char c) { 341 return (c < 128) ? asciiDigits[c] : -1; 342 } 343 } 344 345 /** 346 * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} ( 347 * <code>'\u002D'</code>) is recognized as the minus sign. 348 * 349 * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing 350 * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns 351 * {@code null} if non-ASCII digits are present in the string. 352 * 353 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite 354 * the change to {@link Long#parseLong(String)} for that version. 355 * 356 * @param string the string representation of a long value 357 * @return the long value represented by {@code string}, or {@code null} if {@code string} has a 358 * length of zero or cannot be parsed as a long value 359 * @throws NullPointerException if {@code string} is {@code null} 360 * @since 14.0 361 */ 362 @CheckForNull 363 public static Long tryParse(String string) { 364 return tryParse(string, 10); 365 } 366 367 /** 368 * Parses the specified string as a signed long value using the specified radix. The ASCII 369 * character {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 370 * 371 * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of 372 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 373 * and returns {@code null} if non-ASCII digits are present in the string. 374 * 375 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite 376 * the change to {@link Long#parseLong(String, int)} for that version. 377 * 378 * @param string the string representation of a long value 379 * @param radix the radix to use when parsing 380 * @return the long value represented by {@code string} using {@code radix}, or {@code null} if 381 * {@code string} has a length of zero or cannot be parsed as a long value 382 * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > 383 * Character.MAX_RADIX} 384 * @throws NullPointerException if {@code string} is {@code null} 385 * @since 19.0 386 */ 387 @CheckForNull 388 public static Long tryParse(String string, int radix) { 389 if (checkNotNull(string).isEmpty()) { 390 return null; 391 } 392 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 393 throw new IllegalArgumentException( 394 "radix must be between MIN_RADIX and MAX_RADIX but was " + radix); 395 } 396 boolean negative = string.charAt(0) == '-'; 397 int index = negative ? 1 : 0; 398 if (index == string.length()) { 399 return null; 400 } 401 int digit = AsciiDigits.digit(string.charAt(index++)); 402 if (digit < 0 || digit >= radix) { 403 return null; 404 } 405 long accum = -digit; 406 407 long cap = Long.MIN_VALUE / radix; 408 409 while (index < string.length()) { 410 digit = AsciiDigits.digit(string.charAt(index++)); 411 if (digit < 0 || digit >= radix || accum < cap) { 412 return null; 413 } 414 accum *= radix; 415 if (accum < Long.MIN_VALUE + digit) { 416 return null; 417 } 418 accum -= digit; 419 } 420 421 if (negative) { 422 return accum; 423 } else if (accum == Long.MIN_VALUE) { 424 return null; 425 } else { 426 return -accum; 427 } 428 } 429 430 private static final class LongConverter extends Converter<String, Long> implements Serializable { 431 static final LongConverter INSTANCE = new LongConverter(); 432 433 @Override 434 protected Long doForward(String value) { 435 return Long.decode(value); 436 } 437 438 @Override 439 protected String doBackward(Long value) { 440 return value.toString(); 441 } 442 443 @Override 444 public String toString() { 445 return "Longs.stringConverter()"; 446 } 447 448 private Object readResolve() { 449 return INSTANCE; 450 } 451 452 private static final long serialVersionUID = 1; 453 } 454 455 /** 456 * Returns a serializable converter object that converts between strings and longs using {@link 457 * Long#decode} and {@link Long#toString()}. The returned converter throws {@link 458 * NumberFormatException} if the input string is invalid. 459 * 460 * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed. 461 * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value 462 * {@code 83L}. 463 * 464 * @since 16.0 465 */ 466 public static Converter<String, Long> stringConverter() { 467 return LongConverter.INSTANCE; 468 } 469 470 /** 471 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 472 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 473 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 474 * returned, containing the values of {@code array}, and zeroes in the remaining places. 475 * 476 * @param array the source array 477 * @param minLength the minimum length the returned array must guarantee 478 * @param padding an extra amount to "grow" the array by if growth is necessary 479 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 480 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 481 * minLength} 482 */ 483 public static long[] ensureCapacity(long[] array, int minLength, int padding) { 484 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 485 checkArgument(padding >= 0, "Invalid padding: %s", padding); 486 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 487 } 488 489 /** 490 * Returns a string containing the supplied {@code long} values separated by {@code separator}. 491 * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}. 492 * 493 * @param separator the text that should appear between consecutive values in the resulting string 494 * (but not at the start or end) 495 * @param array an array of {@code long} values, possibly empty 496 */ 497 public static String join(String separator, long... array) { 498 checkNotNull(separator); 499 if (array.length == 0) { 500 return ""; 501 } 502 503 // For pre-sizing a builder, just get the right order of magnitude 504 StringBuilder builder = new StringBuilder(array.length * 10); 505 builder.append(array[0]); 506 for (int i = 1; i < array.length; i++) { 507 builder.append(separator).append(array[i]); 508 } 509 return builder.toString(); 510 } 511 512 /** 513 * Returns a comparator that compares two {@code long} arrays <a 514 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 515 * compares, using {@link #compare(long, long)}), the first pair of values that follow any common 516 * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For 517 * example, {@code [] < [1L] < [1L, 2L] < [2L]}. 518 * 519 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 520 * support only identity equality), but it is consistent with {@link Arrays#equals(long[], 521 * long[])}. 522 * 523 * @since 2.0 524 */ 525 public static Comparator<long[]> lexicographicalComparator() { 526 return LexicographicalComparator.INSTANCE; 527 } 528 529 private enum LexicographicalComparator implements Comparator<long[]> { 530 INSTANCE; 531 532 @Override 533 public int compare(long[] left, long[] right) { 534 int minLength = Math.min(left.length, right.length); 535 for (int i = 0; i < minLength; i++) { 536 int result = Longs.compare(left[i], right[i]); 537 if (result != 0) { 538 return result; 539 } 540 } 541 return left.length - right.length; 542 } 543 544 @Override 545 public String toString() { 546 return "Longs.lexicographicalComparator()"; 547 } 548 } 549 550 /** 551 * Sorts the elements of {@code array} in descending order. 552 * 553 * @since 23.1 554 */ 555 public static void sortDescending(long[] array) { 556 checkNotNull(array); 557 sortDescending(array, 0, array.length); 558 } 559 560 /** 561 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 562 * exclusive in descending order. 563 * 564 * @since 23.1 565 */ 566 public static void sortDescending(long[] array, int fromIndex, int toIndex) { 567 checkNotNull(array); 568 checkPositionIndexes(fromIndex, toIndex, array.length); 569 Arrays.sort(array, fromIndex, toIndex); 570 reverse(array, fromIndex, toIndex); 571 } 572 573 /** 574 * Reverses the elements of {@code array}. This is equivalent to {@code 575 * Collections.reverse(Longs.asList(array))}, but is likely to be more efficient. 576 * 577 * @since 23.1 578 */ 579 public static void reverse(long[] array) { 580 checkNotNull(array); 581 reverse(array, 0, array.length); 582 } 583 584 /** 585 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 586 * exclusive. This is equivalent to {@code 587 * Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 588 * efficient. 589 * 590 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 591 * {@code toIndex > fromIndex} 592 * @since 23.1 593 */ 594 public static void reverse(long[] array, int fromIndex, int toIndex) { 595 checkNotNull(array); 596 checkPositionIndexes(fromIndex, toIndex, array.length); 597 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 598 long tmp = array[i]; 599 array[i] = array[j]; 600 array[j] = tmp; 601 } 602 } 603 604 /** 605 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 606 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 607 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array), 608 * distance)}, but is considerably faster and avoids allocation and garbage collection. 609 * 610 * <p>The provided "distance" may be negative, which will rotate left. 611 * 612 * @since 32.0.0 613 */ 614 public static void rotate(long[] array, int distance) { 615 rotate(array, distance, 0, array.length); 616 } 617 618 /** 619 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 620 * toIndex} exclusive. This is equivalent to {@code 621 * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is 622 * considerably faster and avoids allocations and garbage collection. 623 * 624 * <p>The provided "distance" may be negative, which will rotate left. 625 * 626 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 627 * {@code toIndex > fromIndex} 628 * @since 32.0.0 629 */ 630 public static void rotate(long[] array, int distance, int fromIndex, int toIndex) { 631 // See Ints.rotate for more details about possible algorithms here. 632 checkNotNull(array); 633 checkPositionIndexes(fromIndex, toIndex, array.length); 634 if (array.length <= 1) { 635 return; 636 } 637 638 int length = toIndex - fromIndex; 639 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 640 // places left to rotate. 641 int m = -distance % length; 642 m = (m < 0) ? m + length : m; 643 // The current index of what will become the first element of the rotated section. 644 int newFirstIndex = m + fromIndex; 645 if (newFirstIndex == fromIndex) { 646 return; 647 } 648 649 reverse(array, fromIndex, newFirstIndex); 650 reverse(array, newFirstIndex, toIndex); 651 reverse(array, fromIndex, toIndex); 652 } 653 654 /** 655 * Returns an array containing each value of {@code collection}, converted to a {@code long} value 656 * in the manner of {@link Number#longValue}. 657 * 658 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 659 * Calling this method is as thread-safe as calling that method. 660 * 661 * @param collection a collection of {@code Number} instances 662 * @return an array containing the same values as {@code collection}, in the same order, converted 663 * to primitives 664 * @throws NullPointerException if {@code collection} or any of its elements is null 665 * @since 1.0 (parameter was {@code Collection<Long>} before 12.0) 666 */ 667 public static long[] toArray(Collection<? extends Number> collection) { 668 if (collection instanceof LongArrayAsList) { 669 return ((LongArrayAsList) collection).toLongArray(); 670 } 671 672 Object[] boxedArray = collection.toArray(); 673 int len = boxedArray.length; 674 long[] array = new long[len]; 675 for (int i = 0; i < len; i++) { 676 // checkNotNull for GWT (do not optimize) 677 array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); 678 } 679 return array; 680 } 681 682 /** 683 * Returns a fixed-size list backed by the specified array, similar to {@link 684 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 685 * set a value to {@code null} will result in a {@link NullPointerException}. 686 * 687 * <p>The returned list maintains the values, but not the identities, of {@code Long} objects 688 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 689 * the returned list is unspecified. 690 * 691 * <p>The returned list is serializable. 692 * 693 * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray} 694 * instead, which has an {@link ImmutableLongArray#asList asList} view. 695 * 696 * @param backingArray the array to back the list 697 * @return a list view of the array 698 */ 699 public static List<Long> asList(long... backingArray) { 700 if (backingArray.length == 0) { 701 return Collections.emptyList(); 702 } 703 return new LongArrayAsList(backingArray); 704 } 705 706 @GwtCompatible 707 private static class LongArrayAsList extends AbstractList<Long> 708 implements RandomAccess, Serializable { 709 final long[] array; 710 final int start; 711 final int end; 712 713 LongArrayAsList(long[] array) { 714 this(array, 0, array.length); 715 } 716 717 LongArrayAsList(long[] array, int start, int end) { 718 this.array = array; 719 this.start = start; 720 this.end = end; 721 } 722 723 @Override 724 public int size() { 725 return end - start; 726 } 727 728 @Override 729 public boolean isEmpty() { 730 return false; 731 } 732 733 @Override 734 public Long get(int index) { 735 checkElementIndex(index, size()); 736 return array[start + index]; 737 } 738 739 @Override 740 public boolean contains(@CheckForNull Object target) { 741 // Overridden to prevent a ton of boxing 742 return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; 743 } 744 745 @Override 746 public int indexOf(@CheckForNull Object target) { 747 // Overridden to prevent a ton of boxing 748 if (target instanceof Long) { 749 int i = Longs.indexOf(array, (Long) target, start, end); 750 if (i >= 0) { 751 return i - start; 752 } 753 } 754 return -1; 755 } 756 757 @Override 758 public int lastIndexOf(@CheckForNull Object target) { 759 // Overridden to prevent a ton of boxing 760 if (target instanceof Long) { 761 int i = Longs.lastIndexOf(array, (Long) target, start, end); 762 if (i >= 0) { 763 return i - start; 764 } 765 } 766 return -1; 767 } 768 769 @Override 770 public Long set(int index, Long element) { 771 checkElementIndex(index, size()); 772 long oldValue = array[start + index]; 773 // checkNotNull for GWT (do not optimize) 774 array[start + index] = checkNotNull(element); 775 return oldValue; 776 } 777 778 @Override 779 public List<Long> subList(int fromIndex, int toIndex) { 780 int size = size(); 781 checkPositionIndexes(fromIndex, toIndex, size); 782 if (fromIndex == toIndex) { 783 return Collections.emptyList(); 784 } 785 return new LongArrayAsList(array, start + fromIndex, start + toIndex); 786 } 787 788 @Override 789 public boolean equals(@CheckForNull Object object) { 790 if (object == this) { 791 return true; 792 } 793 if (object instanceof LongArrayAsList) { 794 LongArrayAsList that = (LongArrayAsList) object; 795 int size = size(); 796 if (that.size() != size) { 797 return false; 798 } 799 for (int i = 0; i < size; i++) { 800 if (array[start + i] != that.array[that.start + i]) { 801 return false; 802 } 803 } 804 return true; 805 } 806 return super.equals(object); 807 } 808 809 @Override 810 public int hashCode() { 811 int result = 1; 812 for (int i = start; i < end; i++) { 813 result = 31 * result + Longs.hashCode(array[i]); 814 } 815 return result; 816 } 817 818 @Override 819 public String toString() { 820 StringBuilder builder = new StringBuilder(size() * 10); 821 builder.append('[').append(array[start]); 822 for (int i = start + 1; i < end; i++) { 823 builder.append(", ").append(array[i]); 824 } 825 return builder.append(']').toString(); 826 } 827 828 long[] toLongArray() { 829 return Arrays.copyOfRange(array, start, end); 830 } 831 832 private static final long serialVersionUID = 0; 833 } 834}