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