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.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.Converter;
025import com.google.errorprone.annotations.InlineMe;
026import java.io.Serializable;
027import java.util.AbstractList;
028import java.util.Arrays;
029import java.util.Collection;
030import java.util.Collections;
031import java.util.Comparator;
032import java.util.List;
033import java.util.RandomAccess;
034import javax.annotation.CheckForNull;
035
036/**
037 * Static utility methods pertaining to {@code short} primitives, that are not already found in
038 * either {@link Short} or {@link Arrays}.
039 *
040 * <p>See the Guava User Guide article on <a
041 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
042 *
043 * @author Kevin Bourrillion
044 * @since 1.0
045 */
046@GwtCompatible(emulated = true)
047@ElementTypesAreNonnullByDefault
048public final class Shorts extends ShortsMethodsForWeb {
049  private Shorts() {}
050
051  /**
052   * The number of bytes required to represent a primitive {@code short} value.
053   *
054   * <p><b>Java 8+ users:</b> use {@link Short#BYTES} instead.
055   */
056  public static final int BYTES = Short.SIZE / Byte.SIZE;
057
058  /**
059   * The largest power of two that can be represented as a {@code short}.
060   *
061   * @since 10.0
062   */
063  public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2);
064
065  /**
066   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Short)
067   * value).hashCode()}.
068   *
069   * <p><b>Java 8+ users:</b> use {@link Short#hashCode(short)} instead.
070   *
071   * @param value a primitive {@code short} value
072   * @return a hash code for the value
073   */
074  public static int hashCode(short value) {
075    return value;
076  }
077
078  /**
079   * Returns the {@code short} value that is equal to {@code value}, if possible.
080   *
081   * @param value any value in the range of the {@code short} type
082   * @return the {@code short} value that equals {@code value}
083   * @throws IllegalArgumentException if {@code value} is greater than {@link Short#MAX_VALUE} or
084   *     less than {@link Short#MIN_VALUE}
085   */
086  public static short checkedCast(long value) {
087    short result = (short) value;
088    checkArgument(result == value, "Out of range: %s", value);
089    return result;
090  }
091
092  /**
093   * Returns the {@code short} nearest in value to {@code value}.
094   *
095   * @param value any {@code long} value
096   * @return the same value cast to {@code short} if it is in the range of the {@code short} type,
097   *     {@link Short#MAX_VALUE} if it is too large, or {@link Short#MIN_VALUE} if it is too small
098   */
099  public static short saturatedCast(long value) {
100    if (value > Short.MAX_VALUE) {
101      return Short.MAX_VALUE;
102    }
103    if (value < Short.MIN_VALUE) {
104      return Short.MIN_VALUE;
105    }
106    return (short) value;
107  }
108
109  /**
110   * Compares the two specified {@code short} values. The sign of the value returned is the same as
111   * that of {@code ((Short) a).compareTo(b)}.
112   *
113   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
114   * equivalent {@link Short#compare} method instead.
115   *
116   * @param a the first {@code short} to compare
117   * @param b the second {@code short} to compare
118   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
119   *     greater than {@code b}; or zero if they are equal
120   */
121  @InlineMe(replacement = "Short.compare(a, b)")
122  public static int compare(short a, short b) {
123    return Short.compare(a, b);
124  }
125
126  /**
127   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
128   *
129   * @param array an array of {@code short} values, possibly empty
130   * @param target a primitive {@code short} value
131   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
132   */
133  public static boolean contains(short[] array, short target) {
134    for (short value : array) {
135      if (value == target) {
136        return true;
137      }
138    }
139    return false;
140  }
141
142  /**
143   * Returns the index of the first appearance of the value {@code target} in {@code array}.
144   *
145   * @param array an array of {@code short} values, possibly empty
146   * @param target a primitive {@code short} value
147   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
148   *     such index exists.
149   */
150  public static int indexOf(short[] array, short target) {
151    return indexOf(array, target, 0, array.length);
152  }
153
154  // TODO(kevinb): consider making this public
155  private static int indexOf(short[] array, short target, int start, int end) {
156    for (int i = start; i < end; i++) {
157      if (array[i] == target) {
158        return i;
159      }
160    }
161    return -1;
162  }
163
164  /**
165   * Returns the start position of the first occurrence of the specified {@code target} within
166   * {@code array}, or {@code -1} if there is no such occurrence.
167   *
168   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
169   * i, i + target.length)} contains exactly the same elements as {@code target}.
170   *
171   * @param array the array to search for the sequence {@code target}
172   * @param target the array to search for as a sub-sequence of {@code array}
173   */
174  public static int indexOf(short[] array, short[] target) {
175    checkNotNull(array, "array");
176    checkNotNull(target, "target");
177    if (target.length == 0) {
178      return 0;
179    }
180
181    outer:
182    for (int i = 0; i < array.length - target.length + 1; i++) {
183      for (int j = 0; j < target.length; j++) {
184        if (array[i + j] != target[j]) {
185          continue outer;
186        }
187      }
188      return i;
189    }
190    return -1;
191  }
192
193  /**
194   * Returns the index of the last appearance of the value {@code target} in {@code array}.
195   *
196   * @param array an array of {@code short} values, possibly empty
197   * @param target a primitive {@code short} value
198   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
199   *     such index exists.
200   */
201  public static int lastIndexOf(short[] array, short target) {
202    return lastIndexOf(array, target, 0, array.length);
203  }
204
205  // TODO(kevinb): consider making this public
206  private static int lastIndexOf(short[] array, short target, int start, int end) {
207    for (int i = end - 1; i >= start; i--) {
208      if (array[i] == target) {
209        return i;
210      }
211    }
212    return -1;
213  }
214
215  /**
216   * Returns the least value present in {@code array}.
217   *
218   * @param array a <i>nonempty</i> array of {@code short} values
219   * @return the value present in {@code array} that is less than or equal to every other value in
220   *     the array
221   * @throws IllegalArgumentException if {@code array} is empty
222   */
223  @GwtIncompatible(
224      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
225  public static short min(short... array) {
226    checkArgument(array.length > 0);
227    short min = array[0];
228    for (int i = 1; i < array.length; i++) {
229      if (array[i] < min) {
230        min = array[i];
231      }
232    }
233    return min;
234  }
235
236  /**
237   * Returns the greatest value present in {@code array}.
238   *
239   * @param array a <i>nonempty</i> array of {@code short} values
240   * @return the value present in {@code array} that is greater than or equal to every other value
241   *     in the array
242   * @throws IllegalArgumentException if {@code array} is empty
243   */
244  @GwtIncompatible(
245      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
246  public static short max(short... array) {
247    checkArgument(array.length > 0);
248    short max = array[0];
249    for (int i = 1; i < array.length; i++) {
250      if (array[i] > max) {
251        max = array[i];
252      }
253    }
254    return max;
255  }
256
257  /**
258   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
259   *
260   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
261   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
262   * value} is greater than {@code max}, {@code max} is returned.
263   *
264   * @param value the {@code short} value to constrain
265   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
266   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
267   * @throws IllegalArgumentException if {@code min > max}
268   * @since 21.0
269   */
270  public static short constrainToRange(short value, short min, short max) {
271    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
272    return value < min ? min : value < max ? value : max;
273  }
274
275  /**
276   * Returns the values from each provided array combined into a single array. For example, {@code
277   * concat(new short[] {a, b}, new short[] {}, new short[] {c}} returns the array {@code {a, b,
278   * c}}.
279   *
280   * @param arrays zero or more {@code short} arrays
281   * @return a single array containing all the values from the source arrays, in order
282   * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
283   *     in an {@code int}
284   */
285  public static short[] concat(short[]... arrays) {
286    long length = 0;
287    for (short[] array : arrays) {
288      length += array.length;
289    }
290    short[] result = new short[checkNoOverflow(length)];
291    int pos = 0;
292    for (short[] array : arrays) {
293      System.arraycopy(array, 0, result, pos, array.length);
294      pos += array.length;
295    }
296    return result;
297  }
298
299  private static int checkNoOverflow(long result) {
300    checkArgument(
301        result == (int) result,
302        "the total number of elements (%s) in the arrays must fit in an int",
303        result);
304    return (int) result;
305  }
306
307  /**
308   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
309   * {@code ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value {@code
310   * (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}.
311   *
312   * <p>If you need to convert and concatenate several values (possibly even of different types),
313   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
314   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
315   */
316  @GwtIncompatible // doesn't work
317  public static byte[] toByteArray(short value) {
318    return new byte[] {(byte) (value >> 8), (byte) value};
319  }
320
321  /**
322   * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes
323   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the
324   * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
325   *
326   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
327   * flexibility at little cost in readability.
328   *
329   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
330   */
331  @GwtIncompatible // doesn't work
332  public static short fromByteArray(byte[] bytes) {
333    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
334    return fromBytes(bytes[0], bytes[1]);
335  }
336
337  /**
338   * Returns the {@code short} value whose byte representation is the given 2 bytes, in big-endian
339   * order; equivalent to {@code Shorts.fromByteArray(new byte[] {b1, b2})}.
340   *
341   * @since 7.0
342   */
343  @GwtIncompatible // doesn't work
344  public static short fromBytes(byte b1, byte b2) {
345    return (short) ((b1 << 8) | (b2 & 0xFF));
346  }
347
348  private static final class ShortConverter extends Converter<String, Short>
349      implements Serializable {
350    static final Converter<String, Short> INSTANCE = new ShortConverter();
351
352    @Override
353    protected Short doForward(String value) {
354      return Short.decode(value);
355    }
356
357    @Override
358    protected String doBackward(Short value) {
359      return value.toString();
360    }
361
362    @Override
363    public String toString() {
364      return "Shorts.stringConverter()";
365    }
366
367    private Object readResolve() {
368      return INSTANCE;
369    }
370
371    private static final long serialVersionUID = 1;
372  }
373
374  /**
375   * Returns a serializable converter object that converts between strings and shorts using {@link
376   * Short#decode} and {@link Short#toString()}. The returned converter throws {@link
377   * NumberFormatException} if the input string is invalid.
378   *
379   * <p><b>Warning:</b> please see {@link Short#decode} to understand exactly how strings are
380   * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the
381   * value {@code 83}.
382   *
383   * @since 16.0
384   */
385  public static Converter<String, Short> stringConverter() {
386    return ShortConverter.INSTANCE;
387  }
388
389  /**
390   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
391   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
392   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
393   * returned, containing the values of {@code array}, and zeroes in the remaining places.
394   *
395   * @param array the source array
396   * @param minLength the minimum length the returned array must guarantee
397   * @param padding an extra amount to "grow" the array by if growth is necessary
398   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
399   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
400   *     minLength}
401   */
402  public static short[] ensureCapacity(short[] array, int minLength, int padding) {
403    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
404    checkArgument(padding >= 0, "Invalid padding: %s", padding);
405    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
406  }
407
408  /**
409   * Returns a string containing the supplied {@code short} values separated by {@code separator}.
410   * For example, {@code join("-", (short) 1, (short) 2, (short) 3)} returns the string {@code
411   * "1-2-3"}.
412   *
413   * @param separator the text that should appear between consecutive values in the resulting string
414   *     (but not at the start or end)
415   * @param array an array of {@code short} values, possibly empty
416   */
417  public static String join(String separator, short... array) {
418    checkNotNull(separator);
419    if (array.length == 0) {
420      return "";
421    }
422
423    // For pre-sizing a builder, just get the right order of magnitude
424    StringBuilder builder = new StringBuilder(array.length * 6);
425    builder.append(array[0]);
426    for (int i = 1; i < array.length; i++) {
427      builder.append(separator).append(array[i]);
428    }
429    return builder.toString();
430  }
431
432  /**
433   * Returns a comparator that compares two {@code short} arrays <a
434   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
435   * compares, using {@link #compare(short, short)}), the first pair of values that follow any
436   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
437   * lesser. For example, {@code [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2]}.
438   *
439   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
440   * support only identity equality), but it is consistent with {@link Arrays#equals(short[],
441   * short[])}.
442   *
443   * @since 2.0
444   */
445  public static Comparator<short[]> lexicographicalComparator() {
446    return LexicographicalComparator.INSTANCE;
447  }
448
449  private enum LexicographicalComparator implements Comparator<short[]> {
450    INSTANCE;
451
452    @Override
453    public int compare(short[] left, short[] right) {
454      int minLength = Math.min(left.length, right.length);
455      for (int i = 0; i < minLength; i++) {
456        int result = Short.compare(left[i], right[i]);
457        if (result != 0) {
458          return result;
459        }
460      }
461      return left.length - right.length;
462    }
463
464    @Override
465    public String toString() {
466      return "Shorts.lexicographicalComparator()";
467    }
468  }
469
470  /**
471   * Sorts the elements of {@code array} in descending order.
472   *
473   * @since 23.1
474   */
475  public static void sortDescending(short[] array) {
476    checkNotNull(array);
477    sortDescending(array, 0, array.length);
478  }
479
480  /**
481   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
482   * exclusive in descending order.
483   *
484   * @since 23.1
485   */
486  public static void sortDescending(short[] array, int fromIndex, int toIndex) {
487    checkNotNull(array);
488    checkPositionIndexes(fromIndex, toIndex, array.length);
489    Arrays.sort(array, fromIndex, toIndex);
490    reverse(array, fromIndex, toIndex);
491  }
492
493  /**
494   * Reverses the elements of {@code array}. This is equivalent to {@code
495   * Collections.reverse(Shorts.asList(array))}, but is likely to be more efficient.
496   *
497   * @since 23.1
498   */
499  public static void reverse(short[] array) {
500    checkNotNull(array);
501    reverse(array, 0, array.length);
502  }
503
504  /**
505   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
506   * exclusive. This is equivalent to {@code
507   * Collections.reverse(Shorts.asList(array).subList(fromIndex, toIndex))}, but is likely to be
508   * more efficient.
509   *
510   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
511   *     {@code toIndex > fromIndex}
512   * @since 23.1
513   */
514  public static void reverse(short[] array, int fromIndex, int toIndex) {
515    checkNotNull(array);
516    checkPositionIndexes(fromIndex, toIndex, array.length);
517    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
518      short tmp = array[i];
519      array[i] = array[j];
520      array[j] = tmp;
521    }
522  }
523
524  /**
525   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
526   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
527   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Shorts.asList(array),
528   * distance)}, but is considerably faster and avoids allocation and garbage collection.
529   *
530   * <p>The provided "distance" may be negative, which will rotate left.
531   *
532   * @since 32.0.0
533   */
534  public static void rotate(short[] array, int distance) {
535    rotate(array, distance, 0, array.length);
536  }
537
538  /**
539   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
540   * toIndex} exclusive. This is equivalent to {@code
541   * Collections.rotate(Shorts.asList(array).subList(fromIndex, toIndex), distance)}, but is
542   * considerably faster and avoids allocations and garbage collection.
543   *
544   * <p>The provided "distance" may be negative, which will rotate left.
545   *
546   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
547   *     {@code toIndex > fromIndex}
548   * @since 32.0.0
549   */
550  public static void rotate(short[] array, int distance, int fromIndex, int toIndex) {
551    // See Ints.rotate for more details about possible algorithms here.
552    checkNotNull(array);
553    checkPositionIndexes(fromIndex, toIndex, array.length);
554    if (array.length <= 1) {
555      return;
556    }
557
558    int length = toIndex - fromIndex;
559    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
560    // places left to rotate.
561    int m = -distance % length;
562    m = (m < 0) ? m + length : m;
563    // The current index of what will become the first element of the rotated section.
564    int newFirstIndex = m + fromIndex;
565    if (newFirstIndex == fromIndex) {
566      return;
567    }
568
569    reverse(array, fromIndex, newFirstIndex);
570    reverse(array, newFirstIndex, toIndex);
571    reverse(array, fromIndex, toIndex);
572  }
573
574  /**
575   * Returns an array containing each value of {@code collection}, converted to a {@code short}
576   * value in the manner of {@link Number#shortValue}.
577   *
578   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
579   * Calling this method is as thread-safe as calling that method.
580   *
581   * @param collection a collection of {@code Number} instances
582   * @return an array containing the same values as {@code collection}, in the same order, converted
583   *     to primitives
584   * @throws NullPointerException if {@code collection} or any of its elements is null
585   * @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
586   */
587  public static short[] toArray(Collection<? extends Number> collection) {
588    if (collection instanceof ShortArrayAsList) {
589      return ((ShortArrayAsList) collection).toShortArray();
590    }
591
592    Object[] boxedArray = collection.toArray();
593    int len = boxedArray.length;
594    short[] array = new short[len];
595    for (int i = 0; i < len; i++) {
596      // checkNotNull for GWT (do not optimize)
597      array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
598    }
599    return array;
600  }
601
602  /**
603   * Returns a fixed-size list backed by the specified array, similar to {@link
604   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
605   * set a value to {@code null} will result in a {@link NullPointerException}.
606   *
607   * <p>The returned list maintains the values, but not the identities, of {@code Short} objects
608   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
609   * the returned list is unspecified.
610   *
611   * <p>The returned list is serializable.
612   *
613   * @param backingArray the array to back the list
614   * @return a list view of the array
615   */
616  public static List<Short> asList(short... backingArray) {
617    if (backingArray.length == 0) {
618      return Collections.emptyList();
619    }
620    return new ShortArrayAsList(backingArray);
621  }
622
623  @GwtCompatible
624  private static class ShortArrayAsList extends AbstractList<Short>
625      implements RandomAccess, Serializable {
626    final short[] array;
627    final int start;
628    final int end;
629
630    ShortArrayAsList(short[] array) {
631      this(array, 0, array.length);
632    }
633
634    ShortArrayAsList(short[] array, int start, int end) {
635      this.array = array;
636      this.start = start;
637      this.end = end;
638    }
639
640    @Override
641    public int size() {
642      return end - start;
643    }
644
645    @Override
646    public boolean isEmpty() {
647      return false;
648    }
649
650    @Override
651    public Short get(int index) {
652      checkElementIndex(index, size());
653      return array[start + index];
654    }
655
656    @Override
657    public boolean contains(@CheckForNull Object target) {
658      // Overridden to prevent a ton of boxing
659      return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1;
660    }
661
662    @Override
663    public int indexOf(@CheckForNull Object target) {
664      // Overridden to prevent a ton of boxing
665      if (target instanceof Short) {
666        int i = Shorts.indexOf(array, (Short) target, start, end);
667        if (i >= 0) {
668          return i - start;
669        }
670      }
671      return -1;
672    }
673
674    @Override
675    public int lastIndexOf(@CheckForNull Object target) {
676      // Overridden to prevent a ton of boxing
677      if (target instanceof Short) {
678        int i = Shorts.lastIndexOf(array, (Short) target, start, end);
679        if (i >= 0) {
680          return i - start;
681        }
682      }
683      return -1;
684    }
685
686    @Override
687    public Short set(int index, Short element) {
688      checkElementIndex(index, size());
689      short oldValue = array[start + index];
690      // checkNotNull for GWT (do not optimize)
691      array[start + index] = checkNotNull(element);
692      return oldValue;
693    }
694
695    @Override
696    public List<Short> subList(int fromIndex, int toIndex) {
697      int size = size();
698      checkPositionIndexes(fromIndex, toIndex, size);
699      if (fromIndex == toIndex) {
700        return Collections.emptyList();
701      }
702      return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
703    }
704
705    @Override
706    public boolean equals(@CheckForNull Object object) {
707      if (object == this) {
708        return true;
709      }
710      if (object instanceof ShortArrayAsList) {
711        ShortArrayAsList that = (ShortArrayAsList) object;
712        int size = size();
713        if (that.size() != size) {
714          return false;
715        }
716        for (int i = 0; i < size; i++) {
717          if (array[start + i] != that.array[that.start + i]) {
718            return false;
719          }
720        }
721        return true;
722      }
723      return super.equals(object);
724    }
725
726    @Override
727    public int hashCode() {
728      int result = 1;
729      for (int i = start; i < end; i++) {
730        result = 31 * result + Shorts.hashCode(array[i]);
731      }
732      return result;
733    }
734
735    @Override
736    public String toString() {
737      StringBuilder builder = new StringBuilder(size() * 6);
738      builder.append('[').append(array[start]);
739      for (int i = start + 1; i < end; i++) {
740        builder.append(", ").append(array[i]);
741      }
742      return builder.append(']').toString();
743    }
744
745    short[] toShortArray() {
746      return Arrays.copyOfRange(array, start, end);
747    }
748
749    private static final long serialVersionUID = 0;
750  }
751}