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