Class Shorts
short primitives, that are not already found in
 either Short or Arrays.
 See the Guava User Guide article on primitive utilities.
- Since:
- 1.0
- Author:
- Kevin Bourrillion
- 
Field SummaryFieldsModifier and TypeFieldDescriptionstatic final intThe number of bytes required to represent a primitiveshortvalue.static final shortThe largest power of two that can be represented as ashort.
- 
Method SummaryModifier and TypeMethodDescriptionasList(short... backingArray) Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[]).static shortcheckedCast(long value) Returns theshortvalue that is equal tovalue, if possible.static intcompare(short a, short b) Compares the two specifiedshortvalues.static short[]concat(short[]... arrays) Returns the values from each provided array combined into a single array.static shortconstrainToRange(short value, short min, short max) Returns the value nearest tovaluewhich is within the closed range[min..max].static booleancontains(short[] array, short target) Returnstrueiftargetis present as an element anywhere inarray.static short[]ensureCapacity(short[] array, int minLength, int padding) Returns an array containing the same values asarray, but guaranteed to be of a specified minimum length.static shortfromByteArray(byte[] bytes) Returns theshortvalue whose big-endian representation is stored in the first 2 bytes ofbytes; equivalent toByteBuffer.wrap(bytes).getShort().static shortfromBytes(byte b1, byte b2) Returns theshortvalue whose byte representation is the given 2 bytes, in big-endian order; equivalent toShorts.fromByteArray(new byte[] {b1, b2}).static inthashCode(short value) Returns a hash code forvalue; obsolete alternative toShort.hashCode(short).static intindexOf(short[] array, short target) Returns the index of the first appearance of the valuetargetinarray.static intindexOf(short[] array, short[] target) Returns the start position of the first occurrence of the specifiedtargetwithinarray, or-1if there is no such occurrence.static StringReturns a string containing the suppliedshortvalues separated byseparator.static intlastIndexOf(short[] array, short target) Returns the index of the last appearance of the valuetargetinarray.static Comparator<short[]> Returns a comparator that compares twoshortarrays lexicographically.static shortmax(short... array) Returns the greatest value present inarray.static shortmin(short... array) Returns the least value present inarray.static voidreverse(short[] array) Reverses the elements ofarray.static voidreverse(short[] array, int fromIndex, int toIndex) Reverses the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive.static voidrotate(short[] array, int distance) Performs a right rotation ofarrayof "distance" places, so that the first element is moved to index "distance", and the element at indexiends up at index(distance + i) mod array.length.static voidrotate(short[] array, int distance, int fromIndex, int toIndex) Performs a right rotation ofarraybetweenfromIndexinclusive andtoIndexexclusive.static shortsaturatedCast(long value) Returns theshortnearest in value tovalue.static voidsortDescending(short[] array) Sorts the elements ofarrayin descending order.static voidsortDescending(short[] array, int fromIndex, int toIndex) Sorts the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive in descending order.Returns a serializable converter object that converts between strings and shorts usingShort.decode(java.lang.String)andShort.toString().static short[]toArray(Collection<? extends Number> collection) Returns an array containing each value ofcollection, converted to ashortvalue in the manner ofNumber.shortValue().static byte[]toByteArray(short value) Returns a big-endian representation ofvaluein a 2-element byte array; equivalent toByteBuffer.allocate(2).putShort(value).array().
- 
Field Details- 
BYTESpublic static final int BYTESThe number of bytes required to represent a primitiveshortvalue.Prefer Short.BYTESinstead.- See Also:
 
- 
MAX_POWER_OF_TWOpublic static final short MAX_POWER_OF_TWOThe largest power of two that can be represented as ashort.- Since:
- 10.0
- See Also:
 
 
- 
- 
Method Details- 
hashCodeReturns a hash code forvalue; obsolete alternative toShort.hashCode(short).- Parameters:
- value- a primitive- shortvalue
- Returns:
- a hash code for the value
 
- 
checkedCastpublic static short checkedCast(long value) Returns theshortvalue that is equal tovalue, if possible.- Parameters:
- value- any value in the range of the- shorttype
- Returns:
- the shortvalue that equalsvalue
- Throws:
- IllegalArgumentException- if- valueis greater than- Short.MAX_VALUEor less than- Short.MIN_VALUE
 
- 
saturatedCastpublic static short saturatedCast(long value) Returns theshortnearest in value tovalue.- Parameters:
- value- any- longvalue
- Returns:
- the same value cast to shortif it is in the range of theshorttype,Short.MAX_VALUEif it is too large, orShort.MIN_VALUEif it is too small
 
- 
compareCompares the two specifiedshortvalues. The sign of the value returned is the same as that of((Short) a).compareTo(b).Note: this method is now unnecessary and should be treated as deprecated; use the equivalent Short.compare(short, short)method instead.- Parameters:
- a- the first- shortto compare
- b- the second- shortto compare
- Returns:
- a negative value if ais less thanb; a positive value ifais greater thanb; or zero if they are equal
 
- 
containspublic static boolean contains(short[] array, short target) Returnstrueiftargetis present as an element anywhere inarray.- Parameters:
- array- an array of- shortvalues, possibly empty
- target- a primitive- shortvalue
- Returns:
- trueif- array[i] == targetfor some value of- i
 
- 
indexOfpublic static int indexOf(short[] array, short target) Returns the index of the first appearance of the valuetargetinarray.- Parameters:
- array- an array of- shortvalues, possibly empty
- target- a primitive- shortvalue
- Returns:
- the least index ifor whicharray[i] == target, or-1if no such index exists.
 
- 
indexOfpublic static int indexOf(short[] array, short[] target) Returns the start position of the first occurrence of the specifiedtargetwithinarray, or-1if there is no such occurrence.More formally, returns the lowest index isuch thatArrays.copyOfRange(array, i, i + target.length)contains exactly the same elements astarget.- Parameters:
- array- the array to search for the sequence- target
- target- the array to search for as a sub-sequence of- array
 
- 
lastIndexOfpublic static int lastIndexOf(short[] array, short target) Returns the index of the last appearance of the valuetargetinarray.- Parameters:
- array- an array of- shortvalues, possibly empty
- target- a primitive- shortvalue
- Returns:
- the greatest index ifor whicharray[i] == target, or-1if no such index exists.
 
- 
min@GwtIncompatible("Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static short min(short... array) Returns the least value present inarray.- Parameters:
- array- a nonempty array of- shortvalues
- Returns:
- the value present in arraythat is less than or equal to every other value in the array
- Throws:
- IllegalArgumentException- if- arrayis empty
 
- 
max@GwtIncompatible("Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static short max(short... array) Returns the greatest value present inarray.- Parameters:
- array- a nonempty array of- shortvalues
- Returns:
- the value present in arraythat is greater than or equal to every other value in the array
- Throws:
- IllegalArgumentException- if- arrayis empty
 
- 
constrainToRangepublic static short constrainToRange(short value, short min, short max) Returns the value nearest tovaluewhich is within the closed range[min..max].If valueis within the range[min..max],valueis returned unchanged. Ifvalueis less thanmin,minis returned, and ifvalueis greater thanmax,maxis returned.- Parameters:
- value- the- shortvalue to constrain
- min- the lower bound (inclusive) of the range to constrain- valueto
- max- the upper bound (inclusive) of the range to constrain- valueto
- Throws:
- IllegalArgumentException- if- min > max
- Since:
- 21.0
 
- 
concatpublic static short[] concat(short[]... arrays) 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- shortarrays
- Returns:
- a single array containing all the values from the source arrays, in order
- Throws:
- IllegalArgumentException- if the total number of elements in- arraysdoes not fit in an- int
 
- 
toByteArrayReturns a big-endian representation ofvaluein a 2-element byte array; equivalent toByteBuffer.allocate(2).putShort(value).array(). For example, the input value(short) 0x1234would yield the byte array{0x12, 0x34}.If you need to convert and concatenate several values (possibly even of different types), use a shared ByteBufferinstance, or useByteStreams.newDataOutput()to get a growable buffer.
- 
fromByteArrayReturns theshortvalue whose big-endian representation is stored in the first 2 bytes ofbytes; equivalent toByteBuffer.wrap(bytes).getShort(). For example, the input byte array{0x54, 0x32}would yield theshortvalue0x5432.Arguably, it's preferable to use ByteBuffer; that library exposes much more flexibility at little cost in readability.- Throws:
- IllegalArgumentException- if- byteshas fewer than 2 elements
 
- 
fromBytesReturns theshortvalue whose byte representation is the given 2 bytes, in big-endian order; equivalent toShorts.fromByteArray(new byte[] {b1, b2}).- Since:
- 7.0
 
- 
stringConverterReturns a serializable converter object that converts between strings and shorts usingShort.decode(java.lang.String)andShort.toString(). The returned converter throwsNumberFormatExceptionif the input string is invalid.Warning: please see Short.decode(java.lang.String)to understand exactly how strings are parsed. For example, the string"0123"is treated as octal and converted to the value83.- Since:
- 16.0
 
- 
ensureCapacitypublic static short[] ensureCapacity(short[] array, int minLength, int padding) Returns an array containing the same values asarray, but guaranteed to be of a specified minimum length. Ifarrayalready has a length of at leastminLength, it is returned directly. Otherwise, a new array of sizeminLength + paddingis returned, containing the values ofarray, 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 lengthminLength
- Throws:
- IllegalArgumentException- if- minLengthor- paddingis negative
 
- 
joinReturns a string containing the suppliedshortvalues separated byseparator. 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- shortvalues, possibly empty
 
- 
lexicographicalComparatorReturns a comparator that compares twoshortarrays lexicographically. That is, it compares, usingcompare(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 Object.equals(Object)(since arrays support only identity equality), but it is consistent withArrays.equals(short[], short[]).- Since:
- 2.0
 
- 
sortDescendingpublic static void sortDescending(short[] array) Sorts the elements ofarrayin descending order.- Since:
- 23.1
 
- 
sortDescendingpublic static void sortDescending(short[] array, int fromIndex, int toIndex) Sorts the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive in descending order.- Since:
- 23.1
 
- 
reversepublic static void reverse(short[] array) Reverses the elements ofarray. This is equivalent toCollections.reverse(Shorts.asList(array)), but is likely to be more efficient.- Since:
- 23.1
 
- 
reversepublic static void reverse(short[] array, int fromIndex, int toIndex) Reverses the elements ofarraybetweenfromIndexinclusive andtoIndexexclusive. This is equivalent toCollections.reverse(Shorts.asList(array).subList(fromIndex, toIndex)), but is likely to be more efficient.- Throws:
- IndexOutOfBoundsException- if- fromIndex < 0,- toIndex > array.length, or- toIndex > fromIndex
- Since:
- 23.1
 
- 
rotatepublic static void rotate(short[] array, int distance) Performs a right rotation ofarrayof "distance" places, so that the first element is moved to index "distance", and the element at indexiends up at index(distance + i) mod array.length. This is equivalent toCollections.rotate(Shorts.asList(array), distance), but is considerably faster and avoids allocation and garbage collection.The provided "distance" may be negative, which will rotate left. - Since:
- 32.0.0
 
- 
rotatepublic static void rotate(short[] array, int distance, int fromIndex, int toIndex) Performs a right rotation ofarraybetweenfromIndexinclusive andtoIndexexclusive. This is equivalent toCollections.rotate(Shorts.asList(array).subList(fromIndex, toIndex), distance), but is considerably faster and avoids allocations and garbage collection.The provided "distance" may be negative, which will rotate left. - Throws:
- IndexOutOfBoundsException- if- fromIndex < 0,- toIndex > array.length, or- toIndex > fromIndex
- Since:
- 32.0.0
 
- 
toArrayReturns an array containing each value ofcollection, converted to ashortvalue in the manner ofNumber.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- Numberinstances
- Returns:
- an array containing the same values as collection, in the same order, converted to primitives
- Throws:
- NullPointerException- if- collectionor any of its elements is null
- Since:
- 1.0 (parameter was Collection<Short>before 12.0)
 
- 
asListReturns a fixed-size list backed by the specified array, similar toArrays.asList(Object[]). The list supportsList.set(int, Object), but any attempt to set a value tonullwill result in aNullPointerException.The returned list maintains the values, but not the identities, of Shortobjects written to or read from it. For example, whetherlist.get(0) == list.get(0)is true for the returned list is unspecified.The returned list is serializable. - Parameters:
- backingArray- the array to back the list
- Returns:
- a list view of the array
 
 
-