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