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