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   * @throws NullPointerException if {@code string} is {@code null}
361   * @since 14.0
362   */
363  @Beta
364  @NullableDecl
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>'&#92;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 an 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  @Beta
390  @NullableDecl
391  public static 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 boolean contains(Object target) {
693      // Overridden to prevent a ton of boxing
694      return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
695    }
696
697    @Override
698    public int indexOf(Object target) {
699      // Overridden to prevent a ton of boxing
700      if (target instanceof Long) {
701        int i = Longs.indexOf(array, (Long) target, start, end);
702        if (i >= 0) {
703          return i - start;
704        }
705      }
706      return -1;
707    }
708
709    @Override
710    public int lastIndexOf(Object target) {
711      // Overridden to prevent a ton of boxing
712      if (target instanceof Long) {
713        int i = Longs.lastIndexOf(array, (Long) target, start, end);
714        if (i >= 0) {
715          return i - start;
716        }
717      }
718      return -1;
719    }
720
721    @Override
722    public Long set(int index, Long element) {
723      checkElementIndex(index, size());
724      long oldValue = array[start + index];
725      // checkNotNull for GWT (do not optimize)
726      array[start + index] = checkNotNull(element);
727      return oldValue;
728    }
729
730    @Override
731    public List<Long> subList(int fromIndex, int toIndex) {
732      int size = size();
733      checkPositionIndexes(fromIndex, toIndex, size);
734      if (fromIndex == toIndex) {
735        return Collections.emptyList();
736      }
737      return new LongArrayAsList(array, start + fromIndex, start + toIndex);
738    }
739
740    @Override
741    public boolean equals(@NullableDecl Object object) {
742      if (object == this) {
743        return true;
744      }
745      if (object instanceof LongArrayAsList) {
746        LongArrayAsList that = (LongArrayAsList) object;
747        int size = size();
748        if (that.size() != size) {
749          return false;
750        }
751        for (int i = 0; i < size; i++) {
752          if (array[start + i] != that.array[that.start + i]) {
753            return false;
754          }
755        }
756        return true;
757      }
758      return super.equals(object);
759    }
760
761    @Override
762    public int hashCode() {
763      int result = 1;
764      for (int i = start; i < end; i++) {
765        result = 31 * result + Longs.hashCode(array[i]);
766      }
767      return result;
768    }
769
770    @Override
771    public String toString() {
772      StringBuilder builder = new StringBuilder(size() * 10);
773      builder.append('[').append(array[start]);
774      for (int i = start + 1; i < end; i++) {
775        builder.append(", ").append(array[i]);
776      }
777      return builder.append(']').toString();
778    }
779
780    long[] toLongArray() {
781      return Arrays.copyOfRange(array, start, end);
782    }
783
784    private static final long serialVersionUID = 0;
785  }
786}