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