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.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.base.Converter;
025import java.io.Serializable;
026import java.util.AbstractList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.Comparator;
031import java.util.List;
032import java.util.RandomAccess;
033import java.util.Spliterator;
034import java.util.Spliterators;
035import org.checkerframework.checker.nullness.qual.Nullable;
036
037/**
038 * Static utility methods pertaining to {@code long} primitives, that are not already found in
039 * either {@link Long} or {@link Arrays}.
040 *
041 * <p>See the Guava User Guide article on <a
042 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
043 *
044 * @author Kevin Bourrillion
045 * @since 1.0
046 */
047@GwtCompatible
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  @Beta
239  public static long constrainToRange(long value, long min, long max) {
240    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
241    return Math.min(Math.max(value, min), max);
242  }
243
244  /**
245   * Returns the values from each provided array combined into a single array. For example, {@code
246   * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}.
247   *
248   * @param arrays zero or more {@code long} arrays
249   * @return a single array containing all the values from the source arrays, in order
250   */
251  public static long[] concat(long[]... arrays) {
252    int length = 0;
253    for (long[] array : arrays) {
254      length += array.length;
255    }
256    long[] result = new long[length];
257    int pos = 0;
258    for (long[] array : arrays) {
259      System.arraycopy(array, 0, result, pos, array.length);
260      pos += array.length;
261    }
262    return result;
263  }
264
265  /**
266   * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
267   * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
268   * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
269   * 0x18, 0x19}}.
270   *
271   * <p>If you need to convert and concatenate several values (possibly even of different types),
272   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
273   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
274   */
275  public static byte[] toByteArray(long value) {
276    // Note that this code needs to stay compatible with GWT, which has known
277    // bugs when narrowing byte casts of long values occur.
278    byte[] result = new byte[8];
279    for (int i = 7; i >= 0; i--) {
280      result[i] = (byte) (value & 0xffL);
281      value >>= 8;
282    }
283    return result;
284  }
285
286  /**
287   * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
288   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
289   * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
290   * {@code long} value {@code 0x1213141516171819L}.
291   *
292   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
293   * flexibility at little cost in readability.
294   *
295   * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
296   */
297  public static long fromByteArray(byte[] bytes) {
298    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
299    return fromBytes(
300        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
301  }
302
303  /**
304   * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
305   * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
306   *
307   * @since 7.0
308   */
309  public static long fromBytes(
310      byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
311    return (b1 & 0xFFL) << 56
312        | (b2 & 0xFFL) << 48
313        | (b3 & 0xFFL) << 40
314        | (b4 & 0xFFL) << 32
315        | (b5 & 0xFFL) << 24
316        | (b6 & 0xFFL) << 16
317        | (b7 & 0xFFL) << 8
318        | (b8 & 0xFFL);
319  }
320
321  /*
322   * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs
323   * class.
324   */
325  static final class AsciiDigits {
326    private AsciiDigits() {}
327
328    private static final byte[] asciiDigits;
329
330    static {
331      byte[] result = new byte[128];
332      Arrays.fill(result, (byte) -1);
333      for (int i = 0; i < 10; i++) {
334        result['0' + i] = (byte) i;
335      }
336      for (int i = 0; i < 26; i++) {
337        result['A' + i] = (byte) (10 + i);
338        result['a' + i] = (byte) (10 + i);
339      }
340      asciiDigits = result;
341    }
342
343    static int digit(char c) {
344      return (c < 128) ? asciiDigits[c] : -1;
345    }
346  }
347
348  /**
349   * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} (
350   * <code>'&#92;u002D'</code>) is recognized as the minus sign.
351   *
352   * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
353   * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
354   * {@code null} if non-ASCII digits are present in the string.
355   *
356   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
357   * the change to {@link Long#parseLong(String)} for that version.
358   *
359   * @param string the string representation of a long value
360   * @return the long value represented by {@code string}, or {@code null} if {@code string} has a
361   *     length of zero or cannot be parsed as a long value
362   * @throws NullPointerException if {@code string} is {@code null}
363   * @since 14.0
364   */
365  @Beta
366  public static @Nullable Long tryParse(String string) {
367    return tryParse(string, 10);
368  }
369
370  /**
371   * Parses the specified string as a signed long value using the specified radix. The ASCII
372   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
373   *
374   * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
375   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
376   * and returns {@code null} if non-ASCII digits are present in the string.
377   *
378   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
379   * the change to {@link Long#parseLong(String, int)} for that version.
380   *
381   * @param string the string representation of an long value
382   * @param radix the radix to use when parsing
383   * @return the long value represented by {@code string} using {@code radix}, or {@code null} if
384   *     {@code string} has a length of zero or cannot be parsed as a long value
385   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
386   *     Character.MAX_RADIX}
387   * @throws NullPointerException if {@code string} is {@code null}
388   * @since 19.0
389   */
390  @Beta
391  public static @Nullable Long tryParse(String string, int radix) {
392    if (checkNotNull(string).isEmpty()) {
393      return null;
394    }
395    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
396      throw new IllegalArgumentException(
397          "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
398    }
399    boolean negative = string.charAt(0) == '-';
400    int index = negative ? 1 : 0;
401    if (index == string.length()) {
402      return null;
403    }
404    int digit = AsciiDigits.digit(string.charAt(index++));
405    if (digit < 0 || digit >= radix) {
406      return null;
407    }
408    long accum = -digit;
409
410    long cap = Long.MIN_VALUE / radix;
411
412    while (index < string.length()) {
413      digit = AsciiDigits.digit(string.charAt(index++));
414      if (digit < 0 || digit >= radix || accum < cap) {
415        return null;
416      }
417      accum *= radix;
418      if (accum < Long.MIN_VALUE + digit) {
419        return null;
420      }
421      accum -= digit;
422    }
423
424    if (negative) {
425      return accum;
426    } else if (accum == Long.MIN_VALUE) {
427      return null;
428    } else {
429      return -accum;
430    }
431  }
432
433  private static final class LongConverter extends Converter<String, Long> implements Serializable {
434    static final LongConverter INSTANCE = new LongConverter();
435
436    @Override
437    protected Long doForward(String value) {
438      return Long.decode(value);
439    }
440
441    @Override
442    protected String doBackward(Long value) {
443      return value.toString();
444    }
445
446    @Override
447    public String toString() {
448      return "Longs.stringConverter()";
449    }
450
451    private Object readResolve() {
452      return INSTANCE;
453    }
454
455    private static final long serialVersionUID = 1;
456  }
457
458  /**
459   * Returns a serializable converter object that converts between strings and longs using {@link
460   * Long#decode} and {@link Long#toString()}. The returned converter throws {@link
461   * NumberFormatException} if the input string is invalid.
462   *
463   * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
464   * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
465   * {@code 83L}.
466   *
467   * @since 16.0
468   */
469  @Beta
470  public static Converter<String, Long> stringConverter() {
471    return LongConverter.INSTANCE;
472  }
473
474  /**
475   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
476   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
477   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
478   * returned, containing the values of {@code array}, and zeroes in the remaining places.
479   *
480   * @param array the source array
481   * @param minLength the minimum length the returned array must guarantee
482   * @param padding an extra amount to "grow" the array by if growth is necessary
483   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
484   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
485   *     minLength}
486   */
487  public static long[] ensureCapacity(long[] array, int minLength, int padding) {
488    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
489    checkArgument(padding >= 0, "Invalid padding: %s", padding);
490    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
491  }
492
493  /**
494   * Returns a string containing the supplied {@code long} values separated by {@code separator}.
495   * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}.
496   *
497   * @param separator the text that should appear between consecutive values in the resulting string
498   *     (but not at the start or end)
499   * @param array an array of {@code long} values, possibly empty
500   */
501  public static String join(String separator, long... array) {
502    checkNotNull(separator);
503    if (array.length == 0) {
504      return "";
505    }
506
507    // For pre-sizing a builder, just get the right order of magnitude
508    StringBuilder builder = new StringBuilder(array.length * 10);
509    builder.append(array[0]);
510    for (int i = 1; i < array.length; i++) {
511      builder.append(separator).append(array[i]);
512    }
513    return builder.toString();
514  }
515
516  /**
517   * Returns a comparator that compares two {@code long} arrays <a
518   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
519   * compares, using {@link #compare(long, long)}), the first pair of values that follow any common
520   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
521   * example, {@code [] < [1L] < [1L, 2L] < [2L]}.
522   *
523   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
524   * support only identity equality), but it is consistent with {@link Arrays#equals(long[],
525   * long[])}.
526   *
527   * @since 2.0
528   */
529  public static Comparator<long[]> lexicographicalComparator() {
530    return LexicographicalComparator.INSTANCE;
531  }
532
533  private enum LexicographicalComparator implements Comparator<long[]> {
534    INSTANCE;
535
536    @Override
537    public int compare(long[] left, long[] right) {
538      int minLength = Math.min(left.length, right.length);
539      for (int i = 0; i < minLength; i++) {
540        int result = Longs.compare(left[i], right[i]);
541        if (result != 0) {
542          return result;
543        }
544      }
545      return left.length - right.length;
546    }
547
548    @Override
549    public String toString() {
550      return "Longs.lexicographicalComparator()";
551    }
552  }
553
554  /**
555   * Sorts the elements of {@code array} in descending order.
556   *
557   * @since 23.1
558   */
559  public static void sortDescending(long[] array) {
560    checkNotNull(array);
561    sortDescending(array, 0, array.length);
562  }
563
564  /**
565   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
566   * exclusive in descending order.
567   *
568   * @since 23.1
569   */
570  public static void sortDescending(long[] array, int fromIndex, int toIndex) {
571    checkNotNull(array);
572    checkPositionIndexes(fromIndex, toIndex, array.length);
573    Arrays.sort(array, fromIndex, toIndex);
574    reverse(array, fromIndex, toIndex);
575  }
576
577  /**
578   * Reverses the elements of {@code array}. This is equivalent to {@code
579   * Collections.reverse(Longs.asList(array))}, but is likely to be more efficient.
580   *
581   * @since 23.1
582   */
583  public static void reverse(long[] array) {
584    checkNotNull(array);
585    reverse(array, 0, array.length);
586  }
587
588  /**
589   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
590   * exclusive. This is equivalent to {@code
591   * Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
592   * efficient.
593   *
594   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
595   *     {@code toIndex > fromIndex}
596   * @since 23.1
597   */
598  public static void reverse(long[] array, int fromIndex, int toIndex) {
599    checkNotNull(array);
600    checkPositionIndexes(fromIndex, toIndex, array.length);
601    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
602      long tmp = array[i];
603      array[i] = array[j];
604      array[j] = tmp;
605    }
606  }
607
608  /**
609   * Returns an array containing each value of {@code collection}, converted to a {@code long} value
610   * in the manner of {@link Number#longValue}.
611   *
612   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
613   * Calling this method is as thread-safe as calling that method.
614   *
615   * @param collection a collection of {@code Number} instances
616   * @return an array containing the same values as {@code collection}, in the same order, converted
617   *     to primitives
618   * @throws NullPointerException if {@code collection} or any of its elements is null
619   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
620   */
621  public static long[] toArray(Collection<? extends Number> collection) {
622    if (collection instanceof LongArrayAsList) {
623      return ((LongArrayAsList) collection).toLongArray();
624    }
625
626    Object[] boxedArray = collection.toArray();
627    int len = boxedArray.length;
628    long[] array = new long[len];
629    for (int i = 0; i < len; i++) {
630      // checkNotNull for GWT (do not optimize)
631      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
632    }
633    return array;
634  }
635
636  /**
637   * Returns a fixed-size list backed by the specified array, similar to {@link
638   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
639   * set a value to {@code null} will result in a {@link NullPointerException}.
640   *
641   * <p>The returned list maintains the values, but not the identities, of {@code Long} objects
642   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
643   * the returned list is unspecified.
644   *
645   * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
646   * instead, which has an {@link ImmutableLongArray#asList asList} view.
647   *
648   * @param backingArray the array to back the list
649   * @return a list view of the array
650   */
651  public static List<Long> asList(long... backingArray) {
652    if (backingArray.length == 0) {
653      return Collections.emptyList();
654    }
655    return new LongArrayAsList(backingArray);
656  }
657
658  @GwtCompatible
659  private static class LongArrayAsList extends AbstractList<Long>
660      implements RandomAccess, Serializable {
661    final long[] array;
662    final int start;
663    final int end;
664
665    LongArrayAsList(long[] array) {
666      this(array, 0, array.length);
667    }
668
669    LongArrayAsList(long[] array, int start, int end) {
670      this.array = array;
671      this.start = start;
672      this.end = end;
673    }
674
675    @Override
676    public int size() {
677      return end - start;
678    }
679
680    @Override
681    public boolean isEmpty() {
682      return false;
683    }
684
685    @Override
686    public Long get(int index) {
687      checkElementIndex(index, size());
688      return array[start + index];
689    }
690
691    @Override
692    public Spliterator.OfLong spliterator() {
693      return Spliterators.spliterator(array, start, end, 0);
694    }
695
696    @Override
697    public boolean contains(Object target) {
698      // Overridden to prevent a ton of boxing
699      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
700    }
701
702    @Override
703    public int indexOf(Object target) {
704      // Overridden to prevent a ton of boxing
705      if (target instanceof Long) {
706        int i = Longs.indexOf(array, (Long) target, start, end);
707        if (i >= 0) {
708          return i - start;
709        }
710      }
711      return -1;
712    }
713
714    @Override
715    public int lastIndexOf(Object target) {
716      // Overridden to prevent a ton of boxing
717      if (target instanceof Long) {
718        int i = Longs.lastIndexOf(array, (Long) target, start, end);
719        if (i >= 0) {
720          return i - start;
721        }
722      }
723      return -1;
724    }
725
726    @Override
727    public Long set(int index, Long element) {
728      checkElementIndex(index, size());
729      long oldValue = array[start + index];
730      // checkNotNull for GWT (do not optimize)
731      array[start + index] = checkNotNull(element);
732      return oldValue;
733    }
734
735    @Override
736    public List<Long> subList(int fromIndex, int toIndex) {
737      int size = size();
738      checkPositionIndexes(fromIndex, toIndex, size);
739      if (fromIndex == toIndex) {
740        return Collections.emptyList();
741      }
742      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
743    }
744
745    @Override
746    public boolean equals(@Nullable Object object) {
747      if (object == this) {
748        return true;
749      }
750      if (object instanceof LongArrayAsList) {
751        LongArrayAsList that = (LongArrayAsList) object;
752        int size = size();
753        if (that.size() != size) {
754          return false;
755        }
756        for (int i = 0; i < size; i++) {
757          if (array[start + i] != that.array[that.start + i]) {
758            return false;
759          }
760        }
761        return true;
762      }
763      return super.equals(object);
764    }
765
766    @Override
767    public int hashCode() {
768      int result = 1;
769      for (int i = start; i < end; i++) {
770        result = 31 * result + Longs.hashCode(array[i]);
771      }
772      return result;
773    }
774
775    @Override
776    public String toString() {
777      StringBuilder builder = new StringBuilder(size() * 10);
778      builder.append('[').append(array[start]);
779      for (int i = start + 1; i < end; i++) {
780        builder.append(", ").append(array[i]);
781      }
782      return builder.append(']').toString();
783    }
784
785    long[] toLongArray() {
786      return Arrays.copyOfRange(array, start, end);
787    }
788
789    private static final long serialVersionUID = 0;
790  }
791}