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