Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.primitives;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkElementIndex;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndexes;
 
 
 import java.util.List;
Static utility methods pertaining to short primitives, that are not already found in either java.lang.Short or java.util.Arrays.

See the Guava User Guide article on primitive utilities.

Author(s):
Kevin Bourrillion
Since:
1.0
 
 @GwtCompatible(emulated = true)
 public final class Shorts {
   private Shorts() {}

  
The number of bytes required to represent a primitive short value.
 
   public static final int BYTES = . / .;

  
The largest power of two that can be represented as a short.

Since:
10.0
 
   public static final short MAX_POWER_OF_TWO = 1 << (. - 2);

  
Returns a hash code for value; equal to the result of invoking ((Short) value).hashCode().

Parameters:
value a primitive short value
Returns:
a hash code for the value
 
   public static int hashCode(short value) {
     return value;
   }

  
Returns the short value that is equal to value, if possible.

Parameters:
value any value in the range of the short type
Returns:
the short value that equals value
Throws:
java.lang.IllegalArgumentException if value is greater than java.lang.Short.MAX_VALUE or less than java.lang.Short.MIN_VALUE
 
   public static short checkedCast(long value) {
     short result = (shortvalue;
     checkArgument(result == value"Out of range: %s"value);
     return result;
   }

  
Returns the short nearest in value to value.

Parameters:
value any long value
Returns:
the same value cast to short if it is in the range of the short type, java.lang.Short.MAX_VALUE if it is too large, or java.lang.Short.MIN_VALUE if it is too small
 
   public static short saturatedCast(long value) {
     if (value > .) {
      return .;
    }
    if (value < .) {
      return .;
    }
    return (shortvalue;
  }

  
Compares the two specified short values. The sign of the value returned is the same as that of ((Short) a).compareTo(b).

Parameters:
a the first short to compare
b the second short to compare
Returns:
a negative value if a is less than b; a positive value if a is greater than b; or zero if they are equal
  public static int compare(short ashort b) {
    return a - b// safe due to restricted range
  }

  
Returns true if target is present as an element anywhere in array.

Parameters:
array an array of short values, possibly empty
target a primitive short value
Returns:
true if array[i] == target for some value of i
  public static boolean contains(short[] arrayshort target) {
    for (short value : array) {
      if (value == target) {
        return true;
      }
    }
    return false;
  }

  
Returns the index of the first appearance of the value target in array.

Parameters:
array an array of short values, possibly empty
target a primitive short value
Returns:
the least index i for which array[i] == target, or -1 if no such index exists.
  public static int indexOf(short[] arrayshort target) {
    return indexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int indexOf(
      short[] arrayshort targetint startint end) {
    for (int i = starti < endi++) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the start position of the first occurrence of the specified target within array, or -1 if there is no such occurrence.

More formally, returns the lowest index i such that java.util.Arrays.copyOfRange(array, i, i + target.length) contains exactly the same elements as target.

Parameters:
array the array to search for the sequence target
target the array to search for as a sub-sequence of array
  public static int indexOf(short[] arrayshort[] target) {
    checkNotNull(array"array");
    checkNotNull(target"target");
    if (target.length == 0) {
      return 0;
    }
    outer:
    for (int i = 0; i < array.length - target.length + 1; i++) {
      for (int j = 0; j < target.lengthj++) {
        if (array[i + j] != target[j]) {
          continue outer;
        }
      }
      return i;
    }
    return -1;
  }

  
Returns the index of the last appearance of the value target in array.

Parameters:
array an array of short values, possibly empty
target a primitive short value
Returns:
the greatest index i for which array[i] == target, or -1 if no such index exists.
  public static int lastIndexOf(short[] arrayshort target) {
    return lastIndexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int lastIndexOf(
      short[] arrayshort targetint startint end) {
    for (int i = end - 1; i >= starti--) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the least value present in array.

Parameters:
array a nonempty array of short values
Returns:
the value present in array that is less than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static short min(short... array) {
    checkArgument(array.length > 0);
    short min = array[0];
    for (int i = 1; i < array.lengthi++) {
      if (array[i] < min) {
        min = array[i];
      }
    }
    return min;
  }

  
Returns the greatest value present in array.

Parameters:
array a nonempty array of short values
Returns:
the value present in array that is greater than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static short max(short... array) {
    checkArgument(array.length > 0);
    short max = array[0];
    for (int i = 1; i < array.lengthi++) {
      if (array[i] > max) {
        max = array[i];
      }
    }
    return max;
  }

  
Returns the values from each provided array combined into a single array. For example, concat(new short[] {a, b, new short[] {}, new short[] {c}} returns the array {a, b, c}.

Parameters:
arrays zero or more short arrays
Returns:
a single array containing all the values from the source arrays, in order
  public static short[] concat(short[]... arrays) {
    int length = 0;
    for (short[] array : arrays) {
      length += array.length;
    }
    short[] result = new short[length];
    int pos = 0;
    for (short[] array : arrays) {
      System.arraycopy(array, 0, resultposarray.length);
      pos += array.length;
    }
    return result;
  }

  
Returns a big-endian representation of value in a 2-element byte array; equivalent to ByteBuffer.allocate(2).putShort(value).array(). For example, the input value (short) 0x1234 would yield the byte array {0x12, 0x34}.

If you need to convert and concatenate several values (possibly even of different types), use a shared java.nio.ByteBuffer instance, or use com.google.common.io.ByteStreams.newDataOutput() to get a growable buffer.

  @GwtIncompatible("doesn't work")
  public static byte[] toByteArray(short value) {
    return new byte[] {
        (byte) (value >> 8),
        (bytevalue};
  }

  
Returns the short value whose big-endian representation is stored in the first 2 bytes of bytes; equivalent to ByteBuffer.wrap(bytes).getShort(). For example, the input byte array {0x54, 0x32} would yield the short value 0x5432.

Arguably, it's preferable to use java.nio.ByteBuffer; that library exposes much more flexibility at little cost in readability.

Throws:
java.lang.IllegalArgumentException if bytes has fewer than 2 elements
  @GwtIncompatible("doesn't work")
  public static short fromByteArray(byte[] bytes) {
    checkArgument(bytes.length >= ,
        "array too small: %s < %s"bytes.length);
    return fromBytes(bytes[0], bytes[1]);
  }

  
Returns the short value whose byte representation is the given 2 bytes, in big-endian order; equivalent to Shorts.fromByteArray(new byte[] {b1, b2)}.

Since:
7.0
  @GwtIncompatible("doesn't work")
  public static short fromBytes(byte b1byte b2) {
    return (short) ((b1 << 8) | (b2 & 0xFF));
  }

  
Returns an array containing the same values as array, but guaranteed to be of a specified minimum length. If array already has a length of at least minLength, it is returned directly. Otherwise, a new array of size minLength + padding is returned, containing the values of array, and zeroes in the remaining places.

Parameters:
array the source array
minLength the minimum length the returned array must guarantee
padding an extra amount to "grow" the array by if growth is necessary
Returns:
an array containing the values of array, with guaranteed minimum length minLength
Throws:
java.lang.IllegalArgumentException if minLength or padding is negative
  public static short[] ensureCapacity(
      short[] arrayint minLengthint padding) {
    checkArgument(minLength >= 0, "Invalid minLength: %s"minLength);
    checkArgument(padding >= 0, "Invalid padding: %s"padding);
    return (array.length < minLength)
        ? copyOf(arrayminLength + padding)
        : array;
  }
  // Arrays.copyOf() requires Java 6
  private static short[] copyOf(short[] originalint length) {
    short[] copy = new short[length];
    System.arraycopy(original, 0, copy, 0, Math.min(original.lengthlength));
    return copy;
  }

  
Returns a string containing the supplied short values separated by separator. For example, join("-", (short) 1, (short) 2, (short) 3) returns the string "1-2-3".

Parameters:
separator the text that should appear between consecutive values in the resulting string (but not at the start or end)
array an array of short values, possibly empty
  public static String join(String separatorshort... array) {
    checkNotNull(separator);
    if (array.length == 0) {
      return "";
    }
    // For pre-sizing a builder, just get the right order of magnitude
    StringBuilder builder = new StringBuilder(array.length * 6);
    builder.append(array[0]);
    for (int i = 1; i < array.lengthi++) {
      builder.append(separator).append(array[i]);
    }
    return builder.toString();
  }

  
Returns a comparator that compares two short arrays lexicographically. That is, it compares, using compare(short,short)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example, [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2].

The returned comparator is inconsistent with java.lang.Object.equals(java.lang.Object) (since arrays support only identity equality), but it is consistent with java.util.Arrays.equals(short[],short[]).

Since:
2.0
See also:
Lexicographical order article at Wikipedia
  public static Comparator<short[]> lexicographicalComparator() {
  }
  private enum LexicographicalComparator implements Comparator<short[]> {
    INSTANCE;
    @Override
    public int compare(short[] leftshort[] right) {
      int minLength = Math.min(left.lengthright.length);
      for (int i = 0; i < minLengthi++) {
        int result = Shorts.compare(left[i], right[i]);
        if (result != 0) {
          return result;
        }
      }
      return left.length - right.length;
    }
  }

  
Returns an array containing each value of collection, converted to a short value in the manner of java.lang.Number.shortValue().

Elements are copied from the argument collection as if by collection.toArray(). Calling this method is as thread-safe as calling that method.

Parameters:
collection a collection of Number instances
Returns:
an array containing the same values as collection, in the same order, converted to primitives
Throws:
java.lang.NullPointerException if collection or any of its elements is null
Since:
1.0 (parameter was Collection<Short> before 12.0)
  public static short[] toArray(Collection<? extends Numbercollection) {
    if (collection instanceof ShortArrayAsList) {
      return ((ShortArrayAsListcollection).toShortArray();
    }
    Object[] boxedArray = collection.toArray();
    int len = boxedArray.length;
    short[] array = new short[len];
    for (int i = 0; i < leni++) {
      // checkNotNull for GWT (do not optimize)
      array[i] = ((NumbercheckNotNull(boxedArray[i])).shortValue();
    }
    return array;
  }

  
Returns a fixed-size list backed by the specified array, similar to java.util.Arrays.asList(java.lang.Object[]). The list supports java.util.List.set(int,java.lang.Object), but any attempt to set a value to null will result in a java.lang.NullPointerException.

The returned list maintains the values, but not the identities, of Short objects written to or read from it. For example, whether list.get(0) == list.get(0) is true for the returned list is unspecified.

Parameters:
backingArray the array to back the list
Returns:
a list view of the array
  public static List<ShortasList(short... backingArray) {
    if (backingArray.length == 0) {
      return Collections.emptyList();
    }
    return new ShortArrayAsList(backingArray);
  }
  private static class ShortArrayAsList extends AbstractList<Short>
      implements RandomAccessSerializable {
    final short[] array;
    final int start;
    final int end;
    ShortArrayAsList(short[] array) {
      this(array, 0, array.length);
    }
    ShortArrayAsList(short[] arrayint startint end) {
      this. = array;
      this. = start;
      this. = end;
    }
    @Override public int size() {
      return  - ;
    }
    @Override public boolean isEmpty() {
      return false;
    }
    @Override public Short get(int index) {
      checkElementIndex(indexsize());
      return [ + index];
    }
    @Override public boolean contains(Object target) {
      // Overridden to prevent a ton of boxing
      return (target instanceof Short)
          && Shorts.indexOf(, (Shorttarget) != -1;
    }
    @Override public int indexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Short) {
        int i = Shorts.indexOf(, (Shorttarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public int lastIndexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Short) {
        int i = Shorts.lastIndexOf(, (Shorttarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public Short set(int indexShort element) {
      checkElementIndex(indexsize());
      short oldValue = [ + index];
      [ + index] = checkNotNull(element);  // checkNotNull for GWT (do not optimize)
      return oldValue;
    }
    @Override public List<ShortsubList(int fromIndexint toIndex) {
      int size = size();
      checkPositionIndexes(fromIndextoIndexsize);
      if (fromIndex == toIndex) {
        return Collections.emptyList();
      }
      return new ShortArrayAsList( + fromIndex + toIndex);
    }
    @Override public boolean equals(Object object) {
      if (object == this) {
        return true;
      }
      if (object instanceof ShortArrayAsList) {
        ShortArrayAsList that = (ShortArrayAsListobject;
        int size = size();
        if (that.size() != size) {
          return false;
        }
        for (int i = 0; i < sizei++) {
          if ([ + i] != that.array[that.start + i]) {
            return false;
          }
        }
        return true;
      }
      return super.equals(object);
    }
    @Override public int hashCode() {
      int result = 1;
      for (int i = i < i++) {
        result = 31 * result + Shorts.hashCode([i]);
      }
      return result;
    }
    @Override public String toString() {
      StringBuilder builder = new StringBuilder(size() * 6);
      builder.append('[').append([]);
      for (int i =  + 1; i < i++) {
        builder.append(", ").append([i]);
      }
      return builder.append(']').toString();
    }
    short[] toShortArray() {
      // Arrays.copyOfRange() requires Java 6
      int size = size();
      short[] result = new short[size];
      System.arraycopy(result, 0, size);
      return result;
    }
    private static final long serialVersionUID = 0;
  }
New to GrepCode? Check out our FAQ X