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 org.checkerframework.checker.nullness.compatqual.NullableDecl;
034
035/**
036 * Static utility methods pertaining to {@code long} primitives, that are not already found in
037 * either {@link Long} or {@link Arrays}.
038 *
039 * <p>See the Guava User Guide article on <a
040 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
041 *
042 * @author Kevin Bourrillion
043 * @since 1.0
044 */
045@GwtCompatible
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  @Beta
237  public static long constrainToRange(long value, long min, long max) {
238    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
239    return Math.min(Math.max(value, min), max);
240  }
241
242  /**
243   * Returns the values from each provided array combined into a single array. For example, {@code
244   * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}.
245   *
246   * @param arrays zero or more {@code long} arrays
247   * @return a single array containing all the values from the source arrays, in order
248   */
249  public static long[] concat(long[]... arrays) {
250    int length = 0;
251    for (long[] array : arrays) {
252      length += array.length;
253    }
254    long[] result = new long[length];
255    int pos = 0;
256    for (long[] array : arrays) {
257      System.arraycopy(array, 0, result, pos, array.length);
258      pos += array.length;
259    }
260    return result;
261  }
262
263  /**
264   * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
265   * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
266   * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
267   * 0x18, 0x19}}.
268   *
269   * <p>If you need to convert and concatenate several values (possibly even of different types),
270   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
271   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
272   */
273  public static byte[] toByteArray(long value) {
274    // Note that this code needs to stay compatible with GWT, which has known
275    // bugs when narrowing byte casts of long values occur.
276    byte[] result = new byte[8];
277    for (int i = 7; i >= 0; i--) {
278      result[i] = (byte) (value & 0xffL);
279      value >>= 8;
280    }
281    return result;
282  }
283
284  /**
285   * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
286   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
287   * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
288   * {@code long} value {@code 0x1213141516171819L}.
289   *
290   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
291   * flexibility at little cost in readability.
292   *
293   * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
294   */
295  public static long fromByteArray(byte[] bytes) {
296    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
297    return fromBytes(
298        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
299  }
300
301  /**
302   * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
303   * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
304   *
305   * @since 7.0
306   */
307  public static long fromBytes(
308      byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
309    return (b1 & 0xFFL) << 56
310        | (b2 & 0xFFL) << 48
311        | (b3 & 0xFFL) << 40
312        | (b4 & 0xFFL) << 32
313        | (b5 & 0xFFL) << 24
314        | (b6 & 0xFFL) << 16
315        | (b7 & 0xFFL) << 8
316        | (b8 & 0xFFL);
317  }
318
319  /*
320   * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs
321   * class.
322   */
323  static final class AsciiDigits {
324    private AsciiDigits() {}
325
326    private static final byte[] asciiDigits;
327
328    static {
329      byte[] result = new byte[128];
330      Arrays.fill(result, (byte) -1);
331      for (int i = 0; i <= 9; i++) {
332        result['0' + i] = (byte) i;
333      }
334      for (int i = 0; i <= 26; i++) {
335        result['A' + i] = (byte) (10 + i);
336        result['a' + i] = (byte) (10 + i);
337      }
338      asciiDigits = result;
339    }
340
341    static int digit(char c) {
342      return (c < 128) ? asciiDigits[c] : -1;
343    }
344  }
345
346  /**
347   * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} (
348   * <code>'&#92;u002D'</code>) is recognized as the minus sign.
349   *
350   * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
351   * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
352   * {@code null} if non-ASCII digits are present in the string.
353   *
354   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
355   * the change to {@link Long#parseLong(String)} for that version.
356   *
357   * @param string the string representation of a long value
358   * @return the long value represented by {@code string}, or {@code null} if {@code string} has a
359   *     length of zero or cannot be parsed as a long value
360   * @since 14.0
361   */
362  @Beta
363  @NullableDecl
364  public static Long tryParse(String string) {
365    return tryParse(string, 10);
366  }
367
368  /**
369   * Parses the specified string as a signed long value using the specified radix. The ASCII
370   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
371   *
372   * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
373   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
374   * and returns {@code null} if non-ASCII digits are present in the string.
375   *
376   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
377   * the change to {@link Long#parseLong(String, int)} for that version.
378   *
379   * @param string the string representation of an long value
380   * @param radix the radix to use when parsing
381   * @return the long value represented by {@code string} using {@code radix}, or {@code null} if
382   *     {@code string} has a length of zero or cannot be parsed as a long value
383   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
384   *     Character.MAX_RADIX}
385   * @since 19.0
386   */
387  @Beta
388  @NullableDecl
389  public static Long tryParse(String string, int radix) {
390    if (checkNotNull(string).isEmpty()) {
391      return null;
392    }
393    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
394      throw new IllegalArgumentException(
395          "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
396    }
397    boolean negative = string.charAt(0) == '-';
398    int index = negative ? 1 : 0;
399    if (index == string.length()) {
400      return null;
401    }
402    int digit = AsciiDigits.digit(string.charAt(index++));
403    if (digit < 0 || digit >= radix) {
404      return null;
405    }
406    long accum = -digit;
407
408    long cap = Long.MIN_VALUE / radix;
409
410    while (index < string.length()) {
411      digit = AsciiDigits.digit(string.charAt(index++));
412      if (digit < 0 || digit >= radix || accum < cap) {
413        return null;
414      }
415      accum *= radix;
416      if (accum < Long.MIN_VALUE + digit) {
417        return null;
418      }
419      accum -= digit;
420    }
421
422    if (negative) {
423      return accum;
424    } else if (accum == Long.MIN_VALUE) {
425      return null;
426    } else {
427      return -accum;
428    }
429  }
430
431  private static final class LongConverter extends Converter<String, Long> implements Serializable {
432    static final LongConverter INSTANCE = new LongConverter();
433
434    @Override
435    protected Long doForward(String value) {
436      return Long.decode(value);
437    }
438
439    @Override
440    protected String doBackward(Long value) {
441      return value.toString();
442    }
443
444    @Override
445    public String toString() {
446      return "Longs.stringConverter()";
447    }
448
449    private Object readResolve() {
450      return INSTANCE;
451    }
452
453    private static final long serialVersionUID = 1;
454  }
455
456  /**
457   * Returns a serializable converter object that converts between strings and longs using {@link
458   * Long#decode} and {@link Long#toString()}. The returned converter throws {@link
459   * NumberFormatException} if the input string is invalid.
460   *
461   * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
462   * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
463   * {@code 83L}.
464   *
465   * @since 16.0
466   */
467  @Beta
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   * Returns an array containing each value of {@code collection}, converted to a {@code long} value
608   * in the manner of {@link Number#longValue}.
609   *
610   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
611   * Calling this method is as thread-safe as calling that method.
612   *
613   * @param collection a collection of {@code Number} instances
614   * @return an array containing the same values as {@code collection}, in the same order, converted
615   *     to primitives
616   * @throws NullPointerException if {@code collection} or any of its elements is null
617   * @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
618   */
619  public static long[] toArray(Collection<? extends Number> collection) {
620    if (collection instanceof LongArrayAsList) {
621      return ((LongArrayAsList) collection).toLongArray();
622    }
623
624    Object[] boxedArray = collection.toArray();
625    int len = boxedArray.length;
626    long[] array = new long[len];
627    for (int i = 0; i < len; i++) {
628      // checkNotNull for GWT (do not optimize)
629      array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
630    }
631    return array;
632  }
633
634  /**
635   * Returns a fixed-size list backed by the specified array, similar to {@link
636   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
637   * set a value to {@code null} will result in a {@link NullPointerException}.
638   *
639   * <p>The returned list maintains the values, but not the identities, of {@code Long} objects
640   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
641   * the returned list is unspecified.
642   *
643   * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
644   * instead, which has an {@link ImmutableLongArray#asList asList} view.
645   *
646   * @param backingArray the array to back the list
647   * @return a list view of the array
648   */
649  public static List<Long> asList(long... backingArray) {
650    if (backingArray.length == 0) {
651      return Collections.emptyList();
652    }
653    return new LongArrayAsList(backingArray);
654  }
655
656  @GwtCompatible
657  private static class LongArrayAsList extends AbstractList<Long>
658      implements RandomAccess, Serializable {
659    final long[] array;
660    final int start;
661    final int end;
662
663    LongArrayAsList(long[] array) {
664      this(array, 0, array.length);
665    }
666
667    LongArrayAsList(long[] array, int start, int end) {
668      this.array = array;
669      this.start = start;
670      this.end = end;
671    }
672
673    @Override
674    public int size() {
675      return end - start;
676    }
677
678    @Override
679    public boolean isEmpty() {
680      return false;
681    }
682
683    @Override
684    public Long get(int index) {
685      checkElementIndex(index, size());
686      return array[start + index];
687    }
688
689    @Override
690    public boolean contains(Object target) {
691      // Overridden to prevent a ton of boxing
692      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
693    }
694
695    @Override
696    public int indexOf(Object target) {
697      // Overridden to prevent a ton of boxing
698      if (target instanceof Long) {
699        int i = Longs.indexOf(array, (Long) target, start, end);
700        if (i >= 0) {
701          return i - start;
702        }
703      }
704      return -1;
705    }
706
707    @Override
708    public int lastIndexOf(Object target) {
709      // Overridden to prevent a ton of boxing
710      if (target instanceof Long) {
711        int i = Longs.lastIndexOf(array, (Long) target, start, end);
712        if (i >= 0) {
713          return i - start;
714        }
715      }
716      return -1;
717    }
718
719    @Override
720    public Long set(int index, Long element) {
721      checkElementIndex(index, size());
722      long oldValue = array[start + index];
723      // checkNotNull for GWT (do not optimize)
724      array[start + index] = checkNotNull(element);
725      return oldValue;
726    }
727
728    @Override
729    public List<Long> subList(int fromIndex, int toIndex) {
730      int size = size();
731      checkPositionIndexes(fromIndex, toIndex, size);
732      if (fromIndex == toIndex) {
733        return Collections.emptyList();
734      }
735      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
736    }
737
738    @Override
739    public boolean equals(@NullableDecl Object object) {
740      if (object == this) {
741        return true;
742      }
743      if (object instanceof LongArrayAsList) {
744        LongArrayAsList that = (LongArrayAsList) object;
745        int size = size();
746        if (that.size() != size) {
747          return false;
748        }
749        for (int i = 0; i < size; i++) {
750          if (array[start + i] != that.array[that.start + i]) {
751            return false;
752          }
753        }
754        return true;
755      }
756      return super.equals(object);
757    }
758
759    @Override
760    public int hashCode() {
761      int result = 1;
762      for (int i = start; i < end; i++) {
763        result = 31 * result + Longs.hashCode(array[i]);
764      }
765      return result;
766    }
767
768    @Override
769    public String toString() {
770      StringBuilder builder = new StringBuilder(size() * 10);
771      builder.append('[').append(array[start]);
772      for (int i = start + 1; i < end; i++) {
773        builder.append(", ").append(array[i]);
774      }
775      return builder.append(']').toString();
776    }
777
778    long[] toLongArray() {
779      return Arrays.copyOfRange(array, start, end);
780    }
781
782    private static final long serialVersionUID = 0;
783  }
784}