signature:
public class Strings { /** * Returns the longest string { @ code suffix } such that { @ code a . toString ( ) . endsWith ( suffix ) & &
 * b . toString ( ) . endsWith ( suffix ) } , taking care not to split surrogate pairs . If { @ code a } and
 * { @ code b } have no common suffix , returns the empty string .
 * @ since 11.0 */
public static String commonSuffix ( CharSequence a , CharSequence b ) { } }

implementation: checkNotNull ( a ) ; checkNotNull ( b ) ; int maxSuffixLength = Math . min ( a . length ( ) , b . length ( ) ) ; int s = 0 ; while ( s < maxSuffixLength && a . charAt ( a . length ( ) - s - 1 ) == b . charAt ( b . length ( ) - s - 1 ) ) { s ++ ; } if ( validSurrogatePairAt ( a , a . length ( ) - s - 1 ) || validSurrogatePairAt ( b , b . length ( ) - s - 1 ) ) { s -- ; } return a . subSequence ( a . length ( ) - s , a . length ( ) ) . toString ( ) ;


signature:
public class AggregateFuture { /** * Adds the chain to the seen set , and returns whether all the chain was new to us . */
private static boolean addCausalChain ( Set < Throwable > seen , Throwable t ) { } }

implementation:
for ( ; t != null ; t = t . getCause ( ) ) { boolean firstTimeSeen = seen . add ( t ) ; if ( ! firstTimeSeen ) { /* * We ' ve seen this , so we ' ve seen its causes , too . No need to re - add them . ( There ' s one case
 * where this isn ' t true , but we ignore it : If we record an exception , then someone calls
 * initCause ( ) on it , and then we examine it again , we ' ll conclude that we ' ve seen the whole
 * chain before when it fact we haven ' t . But this should be rare . ) */
return false ; } } return true ;


signature:
public class AbstractMapBasedMultimap { /** * Modification Operations */
@ Override public boolean put ( @ Nullable K key , @ Nullable V value ) { } }

implementation: Collection < V > collection = map . get ( key ) ; if ( collection == null ) { collection = createCollection ( key ) ; if ( collection . add ( value ) ) { totalSize ++ ; map . put ( key , collection ) ; return true ; } else { throw new AssertionError ( "New Collection violated the Collection spec" ) ; } } else if ( collection . add ( value ) ) { totalSize ++ ; return true ; } else { return false ; }


signature:
public class AbstractMapBasedMultimap { /** * { @ inheritDoc }
 * < p > The returned collection is not serializable . */
@ Override public Collection < V > get ( @ Nullable K key ) { } }

implementation: Collection < V > collection = map . get ( key ) ; if ( collection == null ) { collection = createCollection ( key ) ; } return wrapCollection ( key , collection ) ;


signature:
public class AbstractMapBasedMultimap { /** * Generates a decorated collection that remains consistent with the values in the multimap for
 * the provided key . Changes to the multimap may alter the returned collection , and vice versa . */
Collection < V > wrapCollection ( @ Nullable K key , Collection < V > collection ) { } }

implementation: return new WrappedCollection ( key , collection , null ) ;


signature:
public class EnumMultiset { /** * Creates an empty { @ code EnumMultiset } . */
public static < E extends Enum < E > > EnumMultiset < E > create ( Class < E > type ) { } }

implementation: return new EnumMultiset < E > ( type ) ;


signature:
public class EnumMultiset { /** * Returns a new { @ code EnumMultiset } instance containing the given elements . Unlike { @ link
 * EnumMultiset # create ( Iterable ) } , this method does not produce an exception on an empty iterable .
 * @ since 14.0 */
public static < E extends Enum < E > > EnumMultiset < E > create ( Iterable < E > elements , Class < E > type ) { } }

implementation: EnumMultiset < E > result = create ( type ) ; Iterables . addAll ( result , elements ) ; return result ;


signature:
public class EnumMultiset { /** * Returns { @ code element } cast to { @ code E } , if it actually is a nonnull E . Otherwise , throws
 * either a NullPointerException or a ClassCastException as appropriate . */
void checkIsE ( @ NullableDecl Object element ) { } }

implementation: checkNotNull ( element ) ; if ( ! isActuallyE ( element ) ) { throw new ClassCastException ( "Expected an " + type + " but got " + element ) ; }


signature:
public class EnumMultiset { /** * Modification Operations */
@ CanIgnoreReturnValue @ Override public int add ( E element , int occurrences ) { } }

implementation: checkIsE ( element ) ; checkNonnegative ( occurrences , "occurrences" ) ; if ( occurrences == 0 ) { return count ( element ) ; } int index = element . ordinal ( ) ; int oldCount = counts [ index ] ; long newCount = ( long ) oldCount + occurrences ; checkArgument ( newCount <= Integer . MAX_VALUE , "too many occurrences: %s" , newCount ) ; counts [ index ] = ( int ) newCount ; if ( oldCount == 0 ) { distinctElements ++ ; } size += occurrences ; return oldCount ;


signature:
public class EnumMultiset { /** * Modification Operations */
@ CanIgnoreReturnValue @ Override public int setCount ( E element , int count ) { } }

implementation: checkIsE ( element ) ; checkNonnegative ( count , "count" ) ; int index = element . ordinal ( ) ; int oldCount = counts [ index ] ; counts [ index ] = count ; size += count - oldCount ; if ( oldCount == 0 && count > 0 ) { distinctElements ++ ; } else if ( oldCount > 0 && count == 0 ) { distinctElements -- ; } return oldCount ;


signature:
public class CacheBuilder { /** * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry ' s creation , or the most recent replacement of its value .
 * < p > When { @ code duration } is zero , this method hands off to { @ link # maximumSize ( long )
 * maximumSize } { @ code ( 0 ) } , ignoring any otherwise - specified maximum size or weight . This can be
 * useful in testing , or to disable caching temporarily without a code change .
 * < p > Expired entries may be counted in { @ link Cache # size } , but will never be visible to read or
 * write operations . Expired entries are cleaned up as part of the routine maintenance described
 * in the class javadoc .
 * @ param duration the length of time after an entry is created that it should be automatically
 * removed
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalArgumentException if { @ code duration } is negative
 * @ throws IllegalStateException if the time to live or time to idle was already set
 * @ throws ArithmeticException for durations greater than + / - approximately 292 years
 * @ since 25.0 */
@ J2ObjCIncompatible @ GwtIncompatible // java . time . Duration
@ SuppressWarnings ( "GoodTime" ) // java . time . Duration decomposition
public CacheBuilder < K , V > expireAfterWrite ( java . time . Duration duration ) { } }

implementation: return expireAfterWrite ( duration . toNanos ( ) , TimeUnit . NANOSECONDS ) ;


signature:
public class ThreadFactoryBuilder { /** * Sets the naming format to use when naming threads ( { @ link Thread # setName } ) which are created
 * with this ThreadFactory .
 * @ param nameFormat a { @ link String # format ( String , Object . . . ) } - compatible format String , to which
 * a unique integer ( 0 , 1 , etc . ) will be supplied as the single parameter . This integer will
 * be unique to the built instance of the ThreadFactory and will be assigned sequentially . For
 * example , { @ code " rpc - pool - % d " } will generate thread names like { @ code " rpc - pool - 0 " } , { @ code
 * " rpc - pool - 1 " } , { @ code " rpc - pool - 2 " } , etc .
 * @ return this for the builder pattern */
public ThreadFactoryBuilder setNameFormat ( String nameFormat ) { } }

implementation:
String unused = format ( nameFormat , 0 ) ; // fail fast if the format is bad or null
this . nameFormat = nameFormat ; return this ;


signature:
public class ThreadFactoryBuilder { /** * Sets the priority for new threads created with this ThreadFactory .
 * @ param priority the priority for new Threads created with this ThreadFactory
 * @ return this for the builder pattern */
public ThreadFactoryBuilder setPriority ( int priority ) { } }

implementation:
// Thread # setPriority ( ) already checks for validity . These error messages
// are nicer though and will fail - fast .
checkArgument ( priority >= Thread . MIN_PRIORITY , "Thread priority (%s) must be >= %s" , priority , Thread . MIN_PRIORITY ) ; checkArgument ( priority <= Thread . MAX_PRIORITY , "Thread priority (%s) must be <= %s" , priority , Thread . MAX_PRIORITY ) ; this . priority = priority ; return this ;


signature:
public class Suppliers { /** * Returns a supplier that always supplies { @ code instance } . */
public static < T > Supplier < T > ofInstance ( @ NullableDecl T instance ) { } }

implementation: return new SupplierOfInstance < T > ( instance ) ;


signature:
public class TreeMultiset { /** * Creates a new , empty multiset , sorted according to the specified comparator . All elements
 * inserted into the multiset must be < i > mutually comparable < / i > by the specified comparator :
 * { @ code comparator . compare ( e1 , e2 ) } must not throw a { @ code ClassCastException } for any elements
 * { @ code e1 } and { @ code e2 } in the multiset . If the user attempts to add an element to the
 * multiset that violates this constraint , the { @ code add ( Object ) } call will throw a { @ code
 * ClassCastException } .
 * @ param comparator the comparator that will be used to sort this multiset . A null value
 * indicates that the elements ' < i > natural ordering < / i > should be used . */
@ SuppressWarnings ( "unchecked" ) public static < E > TreeMultiset < E > create ( @ NullableDecl Comparator < ? super E > comparator ) { } }

implementation: return ( comparator == null ) ? new TreeMultiset < E > ( ( Comparator ) Ordering . natural ( ) ) : new TreeMultiset < E > ( comparator ) ;


signature:
public class Equivalence { /** * Returns a new equivalence relation for { @ code F } which evaluates equivalence by first applying
 * { @ code function } to the argument , then evaluating using { @ code this } . That is , for any pair of
 * non - null objects { @ code x } and { @ code y } , { @ code equivalence . onResultOf ( function ) . equivalent ( a ,
 * b ) } is true if and only if { @ code equivalence . equivalent ( function . apply ( a ) , function . apply ( b ) ) }
 * is true .
 * < p > For example :
 * < pre > { @ code
 * Equivalence < Person > SAME _ AGE = Equivalence . equals ( ) . onResultOf ( GET _ PERSON _ AGE ) ;
 * } < / pre >
 * < p > { @ code function } will never be invoked with a null value .
 * < p > Note that { @ code function } must be consistent according to { @ code this } equivalence
 * relation . That is , invoking { @ link Function # apply } multiple times for a given value must return
 * equivalent results . For example , { @ code
 * Equivalence . identity ( ) . onResultOf ( Functions . toStringFunction ( ) ) } is broken because it ' s not
 * guaranteed that { @ link Object # toString } ) always returns the same string instance .
 * @ since 10.0 */
public final < F > Equivalence < F > onResultOf ( Function < F , ? extends T > function ) { } }

implementation: return new FunctionalEquivalence < > ( function , this ) ;


signature:
public class Equivalence { /** * Returns a wrapper of { @ code reference } that implements { @ link Wrapper # equals ( Object )
 * Object . equals ( ) } such that { @ code wrap ( a ) . equals ( wrap ( b ) ) } if and only if { @ code equivalent ( a ,
 * @ since 10.0 */
public final < S extends T > Wrapper < S > wrap ( @ NullableDecl S reference ) { } }

implementation: return new Wrapper < S > ( this , reference ) ;


signature:
public class Equivalence { /** * Returns an equivalence over iterables based on the equivalence of their elements . More
 * specifically , two iterables are considered equivalent if they both contain the same number of
 * elements , and each pair of corresponding elements is equivalent according to { @ code this } . Null
 * iterables are equivalent to one another .
 * < p > Note that this method performs a similar function for equivalences as { @ link
 * com . google . common . collect . Ordering # lexicographical } does for orderings .
 * @ since 10.0 */
@ GwtCompatible ( serializable = true ) public final < S extends T > Equivalence < Iterable < S > > pairwise ( ) { } }

implementation:
// Ideally , the returned equivalence would support Iterable < ? extends T > . However ,
// the need for this is so rare that it ' s not worth making callers deal with the ugly wildcard .
return new PairwiseEquivalence < S > ( this ) ;


signature:
public class HostAndPort { /** * Build a HostAndPort instance from separate host and port values .
 * < p > Note : Non - bracketed IPv6 literals are allowed . Use { @ link # requireBracketsForIPv6 ( ) } to
 * prohibit these .
 * @ param host the host string to parse . Must not contain a port number .
 * @ param port a port number from [ 0 . . 65535]
 * @ return if parsing was successful , a populated HostAndPort object .
 * @ throws IllegalArgumentException if { @ code host } contains a port number , or { @ code port } is out
 * of range . */
public static HostAndPort fromParts ( String host , int port ) { } }

implementation: checkArgument ( isValidPort ( port ) , "Port out of range: %s" , port ) ; HostAndPort parsedHost = fromString ( host ) ; checkArgument ( ! parsedHost . hasPort ( ) , "Host has a port: %s" , host ) ; return new HostAndPort ( parsedHost . host , port , parsedHost . hasBracketlessColons ) ;


signature:
public class HostAndPort { /** * Build a HostAndPort instance from a host only .
 * < p > Note : Non - bracketed IPv6 literals are allowed . Use { @ link # requireBracketsForIPv6 ( ) } to
 * prohibit these .
 * @ param host the host - only string to parse . Must not contain a port number .
 * @ return if parsing was successful , a populated HostAndPort object .
 * @ throws IllegalArgumentException if { @ code host } contains a port number .
 * @ since 17.0 */
public static HostAndPort fromHost ( String host ) { } }

implementation: HostAndPort parsedHost = fromString ( host ) ; checkArgument ( ! parsedHost . hasPort ( ) , "Host has a port: %s" , host ) ; return parsedHost ;


signature:
public class HostAndPort { /** * Split a freeform string into a host and port , without strict validation .
 * < p > Note that the host - only formats will leave the port field undefined . You can use { @ link
 * # withDefaultPort ( int ) } to patch in a default value .
 * @ param hostPortString the input string to parse .
 * @ return if parsing was successful , a populated HostAndPort object .
 * @ throws IllegalArgumentException if nothing meaningful could be parsed . */
public static HostAndPort fromString ( String hostPortString ) { } }

implementation:
checkNotNull ( hostPortString ) ; String host ; String portString = null ; boolean hasBracketlessColons = false ; if ( hostPortString . startsWith ( "[" ) ) { String [ ] hostAndPort = getHostAndPortFromBracketedHost ( hostPortString ) ; host = hostAndPort [ 0 ] ; portString = hostAndPort [ 1 ] ; } else { int colonPos = hostPortString . indexOf ( ':' ) ; if ( colonPos >= 0 && hostPortString . indexOf ( ':' , colonPos + 1 ) == - 1 ) { // Exactly 1 colon . Split into host : port .
host = hostPortString . substring ( 0 , colonPos ) ; portString = hostPortString . substring ( colonPos + 1 ) ; } else { // 0 or 2 + colons . Bare hostname or IPv6 literal .
host = hostPortString ; hasBracketlessColons = ( colonPos >= 0 ) ; } } int port = NO_PORT ; if ( ! Strings . isNullOrEmpty ( portString ) ) { // Try to parse the whole port string as a number .
// JDK7 accepts leading plus signs . We don ' t want to .
checkArgument ( ! portString . startsWith ( "+" ) , "Unparseable port number: %s" , hostPortString ) ; try { port = Integer . parseInt ( portString ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Unparseable port number: " + hostPortString ) ; } checkArgument ( isValidPort ( port ) , "Port number out of range: %s" , hostPortString ) ; } return new HostAndPort ( host , port , hasBracketlessColons ) ;


signature:
public class HostAndPort { /** * Parses a bracketed host - port string , throwing IllegalArgumentException if parsing fails .
 * @ param hostPortString the full bracketed host - port specification . Post might not be specified .
 * @ return an array with 2 strings : host and port , in that order .
 * @ throws IllegalArgumentException if parsing the bracketed host - port string fails . */
private static String [ ] getHostAndPortFromBracketedHost ( String hostPortString ) { } }

implementation: int colonIndex = 0 ; int closeBracketIndex = 0 ; checkArgument ( hostPortString . charAt ( 0 ) == '[' , "Bracketed host-port string must start with a bracket: %s" , hostPortString ) ; colonIndex = hostPortString . indexOf ( ':' ) ; closeBracketIndex = hostPortString . lastIndexOf ( ']' ) ; checkArgument ( colonIndex > - 1 && closeBracketIndex > colonIndex , "Invalid bracketed host/port: %s" , hostPortString ) ; String host = hostPortString . substring ( 1 , closeBracketIndex ) ; if ( closeBracketIndex + 1 == hostPortString . length ( ) ) { return new String [ ] { host , "" } ; } else { checkArgument ( hostPortString . charAt ( closeBracketIndex + 1 ) == ':' , "Only a colon may follow a close bracket: %s" , hostPortString ) ; for ( int i = closeBracketIndex + 2 ; i < hostPortString . length ( ) ; ++ i ) { checkArgument ( Character . isDigit ( hostPortString . charAt ( i ) ) , "Port must be numeric: %s" , hostPortString ) ; } return new String [ ] { host , hostPortString . substring ( closeBracketIndex + 2 ) } ; }


signature:
public class Shorts { /** * Returns the { @ code short } nearest in value to { @ code value } .
 * @ param value any { @ code long } value
 * @ return the same value cast to { @ code short } if it is in the range of the { @ code short } type ,
 * { @ link Short # MAX _ VALUE } if it is too large , or { @ link Short # MIN _ VALUE } if it is too small */
public static short saturatedCast ( long value ) { } }

implementation: if ( value > Short . MAX_VALUE ) { return Short . MAX_VALUE ; } if ( value < Short . MIN_VALUE ) { return Short . MIN_VALUE ; } return ( short ) value ;


signature:
public class Shorts { /** * Returns an array containing each value of { @ code collection } , converted to a { @ code short }
 * value in the manner of { @ link Number # shortValue } .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * @ param collection a collection of { @ code Number } instances
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null
 * @ since 1.0 ( parameter was { @ code Collection < Short > } before 12.0) */
public static short [ ] toArray ( Collection < ? extends Number > collection ) { } }

implementation:
if ( collection instanceof ShortArrayAsList ) { return ( ( ShortArrayAsList ) collection ) . toShortArray ( ) ; } Object [ ] boxedArray = collection . toArray ( ) ; int len = boxedArray . length ; short [ ] array = new short [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { // checkNotNull for GWT ( do not optimize )
array [ i ] = ( ( Number ) checkNotNull ( boxedArray [ i ] ) ) . shortValue ( ) ; } return array ;


signature:
public class Shorts { /** * Returns a fixed - size list backed by the specified array , similar to { @ link
 * Arrays # asList ( Object [ ] ) } . The list supports { @ link List # set ( int , Object ) } , but any attempt to
 * set a value to { @ code null } will result in a { @ link NullPointerException } .
 * < p > The returned list maintains the values , but not the identities , of { @ code Short } objects
 * written to or read from it . For example , whether { @ code list . get ( 0 ) = = list . get ( 0 ) } is true for
 * the returned list is unspecified .
 * @ param backingArray the array to back the list
 * @ return a list view of the array */
public static List < Short > asList ( short ... backingArray ) { } }

implementation: if ( backingArray . length == 0 ) { return Collections . emptyList ( ) ; } return new ShortArrayAsList ( backingArray ) ;


signature:
public class EnumMultiset { /** * Returns { @ code element } cast to { @ code E } , if it actually is a nonnull E . Otherwise , throws
 * either a NullPointerException or a ClassCastException as appropriate . */
void checkIsE ( @ Nullable Object element ) { } }

implementation: checkNotNull ( element ) ; if ( ! isActuallyE ( element ) ) { throw new ClassCastException ( "Expected an " + type + " but got " + element ) ; }


signature:
public class EnumMultiset { /** * Modification Operations */
@ CanIgnoreReturnValue @ Override public int remove ( @ Nullable Object element , int occurrences ) { } }

implementation: if ( element == null || ! isActuallyE ( element ) ) { return 0 ; } Enum < ? > e = ( Enum < ? > ) element ; checkNonnegative ( occurrences , "occurrences" ) ; if ( occurrences == 0 ) { return count ( element ) ; } int index = e . ordinal ( ) ; int oldCount = counts [ index ] ; if ( oldCount == 0 ) { return 0 ; } else if ( oldCount <= occurrences ) { counts [ index ] = 0 ; distinctElements -- ; size -= oldCount ; } else { counts [ index ] = oldCount - occurrences ; size -= occurrences ; } return oldCount ;


signature:
public class StandardTable { /** * Accessors */
@ Override public boolean contains ( @ Nullable Object rowKey , @ Nullable Object columnKey ) { } }

implementation: return rowKey != null && columnKey != null && super . contains ( rowKey , columnKey ) ;


signature:
public class Longs { /** * Returns a big - endian representation of { @ code value } in an 8 - element byte array ; equivalent to
 * { @ code ByteBuffer . allocate ( 8 ) . putLong ( value ) . array ( ) } . For example , the input value { @ code
 * 0x1213141516171819L } would yield the byte array { @ code { 0x12 , 0x13 , 0x14 , 0x15 , 0x16 , 0x17,
 * 0x18 , 0x19 } } .
 * < p > If you need to convert and concatenate several values ( possibly even of different types ) ,
 * use a shared { @ link java . nio . ByteBuffer } instance , or use { @ link
 * com . google . common . io . ByteStreams # newDataOutput ( ) } to get a growable buffer . */
public static byte [ ] toByteArray ( long value ) { } }

implementation:
// Note that this code needs to stay compatible with GWT , which has known
// bugs when narrowing byte casts of long values occur .
byte [ ] result = new byte [ 8 ] ; for ( int i = 7 ; i >= 0 ; i -- ) { result [ i ] = ( byte ) ( value & 0xffL ) ; value >>= 8 ; } return result ;


signature:
public class Longs { /** * Returns the { @ code long } value whose byte representation is the given 8 bytes , in big - endian
 * order ; equivalent to { @ code Longs . fromByteArray ( new byte [ ] { b1 , b2 , b3 , b4 , b5 , b6 , b7 , b8 } ) } .
 * @ since 7.0 */
public static long fromBytes ( byte b1 , byte b2 , byte b3 , byte b4 , byte b5 , byte b6 , byte b7 , byte b8 ) { } }


signature:
public class Longs { /** * Returns a string containing the supplied { @ code long } values separated by { @ code separator } .
 * For example , { @ code join ( " - " , 1L , 2L , 3L ) } returns the string { @ code " 1-2-3 " } .
 * @ param separator the text that should appear between consecutive values in the resulting string
 * ( but not at the start or end )
 * @ param array an array of { @ code long } values , possibly empty */
public static String join ( String separator , long ... array ) { } }

implementation:
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 * 10 ) ; builder . append ( array [ 0 ] ) ; for ( int i = 1 ; i < array . length ; i ++ ) { builder . append ( separator ) . append ( array [ i ] ) ; } return builder . toString ( ) ;


signature:
public class Longs { /** * Returns an array containing each value of { @ code collection } , converted to a { @ code long } value
 * in the manner of { @ link Number # longValue } .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * @ param collection a collection of { @ code Number } instances
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null
 * @ since 1.0 ( parameter was { @ code Collection < Long > } before 12.0) */
public static long [ ] toArray ( Collection < ? extends Number > collection ) { } }

implementation:
if ( collection instanceof LongArrayAsList ) { return ( ( LongArrayAsList ) collection ) . toLongArray ( ) ; } Object [ ] boxedArray = collection . toArray ( ) ; int len = boxedArray . length ; long [ ] array = new long [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { // checkNotNull for GWT ( do not optimize )
array [ i ] = ( ( Number ) checkNotNull ( boxedArray [ i ] ) ) . longValue ( ) ; } return array ;


signature:
public class Longs { /** * Returns a fixed - size list backed by the specified array , similar to { @ link
 * Arrays # asList ( Object [ ] ) } . The list supports { @ link List # set ( int , Object ) } , but any attempt to
 * set a value to { @ code null } will result in a { @ link NullPointerException } .
 * < p > The returned list maintains the values , but not the identities , of { @ code Long } objects
 * written to or read from it . For example , whether { @ code list . get ( 0 ) = = list . get ( 0 ) } is true for
 * the returned list is unspecified .
 * < p > < b > Note : < / b > when possible , you should represent your data as an { @ link ImmutableLongArray }
 * instead , which has an { @ link ImmutableLongArray # asList asList } view .
 * @ param backingArray the array to back the list
 * @ return a list view of the array */
public static List < Long > asList ( long ... backingArray ) { } }

implementation: if ( backingArray . length == 0 ) { return Collections . emptyList ( ) ; } return new LongArrayAsList ( backingArray ) ;


signature:
public class GeneralRange { /** * Converts a Range to a GeneralRange . */
static < T extends Comparable > GeneralRange < T > from ( Range < T > range ) { } }

implementation: @ Nullable T lowerEndpoint = range . hasLowerBound ( ) ? range . lowerEndpoint ( ) : null ; BoundType lowerBoundType = range . hasLowerBound ( ) ? range . lowerBoundType ( ) : OPEN ; @ Nullable T upperEndpoint = range . hasUpperBound ( ) ? range . upperEndpoint ( ) : null ; BoundType upperBoundType = range . hasUpperBound ( ) ? range . upperBoundType ( ) : OPEN ; return new GeneralRange < T > ( Ordering . natural ( ) , range . hasLowerBound ( ) , lowerEndpoint , lowerBoundType , range . hasUpperBound ( ) , upperEndpoint , upperBoundType ) ;


signature:
public class GeneralRange { /** * Returns the whole range relative to the specified comparator . */
static < T > GeneralRange < T > all ( Comparator < ? super T > comparator ) { } }

implementation: return new GeneralRange < T > ( comparator , false , null , OPEN , false , null , OPEN ) ;


signature:
public class GeneralRange { /** * Returns everything above the endpoint relative to the specified comparator , with the specified
 * endpoint behavior . */
static < T > GeneralRange < T > downTo ( Comparator < ? super T > comparator , @ Nullable T endpoint , BoundType boundType ) { } }

implementation: return new GeneralRange < T > ( comparator , true , endpoint , boundType , false , null , OPEN ) ;


signature:
public class GeneralRange { /** * Returns everything between the endpoints relative to the specified comparator , with the
 * specified endpoint behavior . */
static < T > GeneralRange < T > range ( Comparator < ? super T > comparator , @ Nullable T lower , BoundType lowerType , @ Nullable T upper , BoundType upperType ) { } }

implementation: return new GeneralRange < T > ( comparator , true , lower , lowerType , true , upper , upperType ) ;


signature:
public class GeneralRange { /** * Returns the intersection of the two ranges , or an empty range if their intersection is empty . */
GeneralRange < T > intersect ( GeneralRange < T > other ) { } }

implementation:
checkNotNull ( other ) ; checkArgument ( comparator . equals ( other . comparator ) ) ; boolean hasLowBound = this . hasLowerBound ; @ Nullable T lowEnd = getLowerEndpoint ( ) ; BoundType lowType = getLowerBoundType ( ) ; if ( ! hasLowerBound ( ) ) { hasLowBound = other . hasLowerBound ; lowEnd = other . getLowerEndpoint ( ) ; lowType = other . getLowerBoundType ( ) ; } else if ( other . hasLowerBound ( ) ) { int cmp = comparator . compare ( getLowerEndpoint ( ) , other . getLowerEndpoint ( ) ) ; if ( cmp < 0 || ( cmp == 0 && other . getLowerBoundType ( ) == OPEN ) ) { lowEnd = other . getLowerEndpoint ( ) ; lowType = other . getLowerBoundType ( ) ; } } boolean hasUpBound = this . hasUpperBound ; @ Nullable T upEnd = getUpperEndpoint ( ) ; BoundType upType = getUpperBoundType ( ) ; if ( ! hasUpperBound ( ) ) { hasUpBound = other . hasUpperBound ; upEnd = other . getUpperEndpoint ( ) ; upType = other . getUpperBoundType ( ) ; } else if ( other . hasUpperBound ( ) ) { int cmp = comparator . compare ( getUpperEndpoint ( ) , other . getUpperEndpoint ( ) ) ; if ( cmp > 0 || ( cmp == 0 && other . getUpperBoundType ( ) == OPEN ) ) { upEnd = other . getUpperEndpoint ( ) ; upType = other . getUpperBoundType ( ) ; } } if ( hasLowBound && hasUpBound ) { int cmp = comparator . compare ( lowEnd , upEnd ) ; if ( cmp > 0 || ( cmp == 0 && lowType == OPEN && upType == OPEN ) ) { // force allowed empty range
lowEnd = upEnd ; lowType = OPEN ; upType = CLOSED ; } } return new GeneralRange < T > ( comparator , hasLowBound , lowEnd , lowType , hasUpBound , upEnd , upType ) ;


signature:
public class GeneralRange { /** * Returns the same range relative to the reversed comparator . */
GeneralRange < T > reverse ( ) { } }

implementation: GeneralRange < T > result = reverse ; if ( result == null ) { result = new GeneralRange < T > ( Ordering . from ( comparator ) . reverse ( ) , hasUpperBound , getUpperEndpoint ( ) , getUpperBoundType ( ) , hasLowerBound , getLowerEndpoint ( ) , getLowerBoundType ( ) ) ; result . reverse = this ; return this . reverse = result ; } return result ;


signature:
public class ImmutableSet { /** * the elements are known to be non - null . */
static < E > ImmutableSet < E > unsafeDelegate ( Set < E > delegate ) { } }

implementation: switch ( delegate . size ( ) ) { case 0 : return of ( ) ; case 1 : return new SingletonImmutableSet < E > ( delegate . iterator ( ) . next ( ) ) ; default : return new RegularImmutableSet < E > ( delegate ) ; }


signature:
public class ImmutableMap { /** * Returns an immutable map containing a single entry . This map behaves and performs comparably to
 * { @ link Collections # singletonMap } but will not accept a null key or value . It is preferable
 * mainly for consistency and maintainability of your code . */
public static < K , V > ImmutableMap < K , V > of ( K k1 , V v1 ) { } }

implementation: checkEntryNotNull ( k1 , v1 ) ; return RegularImmutableMap . create ( 1 , new Object [ ] { k1 , v1 } ) ;


signature:
public class ImmutableMap { /** * Returns an immutable map containing the given entries , in order .
 * @ throws IllegalArgumentException if duplicate keys are provided */
public static < K , V > ImmutableMap < K , V > of ( K k1 , V v1 , K k2 , V v2 , K k3 , V v3 ) { } }

implementation: checkEntryNotNull ( k1 , v1 ) ; checkEntryNotNull ( k2 , v2 ) ; checkEntryNotNull ( k3 , v3 ) ; return RegularImmutableMap . create ( 3 , new Object [ ] { k1 , v1 , k2 , v2 , k3 , v3 } ) ;


signature:
public class ImmutableMap { /** * Returns an immutable map containing the same entries as { @ code map } . The returned map iterates
 * over entries in the same order as the { @ code entrySet } of the original map . If { @ code map }
 * somehow contains entries with duplicate keys ( for example , if it is a { @ code SortedMap } whose
 * comparator is not < i > consistent with equals < / i > ) , the results of this method are undefined .
 * < p > Despite the method name , this method attempts to avoid actually copying the data when it is
 * safe to do so . The exact circumstances under which a copy will or will not be performed are
 * undocumented and subject to change .
 * @ throws NullPointerException if any key or value in { @ code map } is null */
public static < K , V > ImmutableMap < K , V > copyOf ( Map < ? extends K , ? extends V > map ) { } }

implementation:
if ( ( map instanceof ImmutableMap ) && ! ( map instanceof SortedMap ) ) { @ SuppressWarnings ( "unchecked" ) // safe since map is not writable
ImmutableMap < K , V > kvMap = ( ImmutableMap < K , V > ) map ; if ( ! kvMap . isPartialView ( ) ) { return kvMap ; } } return copyOf ( map . entrySet ( ) ) ;


signature:
public class ImmutableMap { /** * Returns an immutable map containing the specified entries . The returned map iterates over
 * entries in the same order as the original iterable .
 * @ throws NullPointerException if any key , value , or entry is null
 * @ throws IllegalArgumentException if two entries have the same key
 * @ since 19.0 */
@ Beta public static < K , V > ImmutableMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { } }

implementation: int initialCapacity = ( entries instanceof Collection ) ? ( ( Collection < ? > ) entries ) . size ( ) : ImmutableCollection . Builder . DEFAULT_INITIAL_CAPACITY ; ImmutableMap . Builder < K , V > builder = new ImmutableMap . Builder < K , V > ( initialCapacity ) ; builder . putAll ( entries ) ; return builder . build ( ) ;


signature:
public class ImmutableCollection { /** * Returns an { @ code ImmutableList } containing the same elements , in the same order , as this
 * collection .
 * < p > < b > Performance note : < / b > in most cases this method can return quickly without actually
 * copying anything . The exact circumstances under which the copy is performed are undefined and
 * subject to change .
 * @ since 2.0 */
public ImmutableList < E > asList ( ) { } }

implementation: return isEmpty ( ) ? ImmutableList . < E > of ( ) : ImmutableList . < E > asImmutableList ( toArray ( ) ) ;


signature:
public class LinkedHashMultiset { /** * Creates a new { @ code LinkedHashMultiset } containing the specified elements .
 * < p > This implementation is highly efficient when { @ code elements } is itself a { @ link Multiset } .
 * @ param elements the elements that the multiset should contain */
public static < E > LinkedHashMultiset < E > create ( Iterable < ? extends E > elements ) { } }

implementation: LinkedHashMultiset < E > multiset = create ( Multisets . inferDistinctElements ( elements ) ) ; Iterables . addAll ( multiset , elements ) ; return multiset ;


signature:
public class TreeRangeMap { /** * Returns the range that spans the given range and entry , if the entry can be coalesced . */
private static < K extends Comparable , V > Range < K > coalesce ( Range < K > range , V value , @ NullableDecl Entry < Cut < K > , RangeMapEntry < K , V > > entry ) { } }

implementation: if ( entry != null && entry . getValue ( ) . getKey ( ) . isConnected ( range ) && entry . getValue ( ) . getValue ( ) . equals ( value ) ) { return range . span ( entry . getValue ( ) . getKey ( ) ) ; } return range ;


signature:
public class Strings { /** * TODO ( diamondm ) consider using Arrays . toString ( ) for array parameters */
public static String lenientFormat ( @ NullableDecl String template , @ NullableDecl Object ... args ) { } }

implementation:
template = String . valueOf ( template ) ; // null - > " null "
if ( args == null ) { args = new Object [ ] { "(Object[])null" } ; } else { for ( int i = 0 ; i < args . length ; i ++ ) { args [ i ] = lenientToString ( args [ i ] ) ; } } // start substituting the arguments into the ' % s ' placeholders
StringBuilder builder = new StringBuilder ( template . length ( ) + 16 * args . length ) ; int templateStart = 0 ; int i = 0 ; while ( i < args . length ) { int placeholderStart = template . indexOf ( "%s" , templateStart ) ; if ( placeholderStart == - 1 ) { break ; } builder . append ( template , templateStart , placeholderStart ) ; builder . append ( args [ i ++ ] ) ; templateStart = placeholderStart + 2 ; } builder . append ( template , templateStart , template . length ( ) ) ; // if we run out of placeholders , append the extra args in square braces
if ( i < args . length ) { builder . append ( " [" ) ; builder . append ( args [ i ++ ] ) ; while ( i < args . length ) { builder . append ( ", " ) ; builder . append ( args [ i ++ ] ) ; } builder . append ( ']' ) ; } return builder . toString ( ) ;


signature:
public class Types { /** * Returns the array type of { @ code componentType } . */
static Type newArrayType ( Type componentType ) { } }

implementation: if ( componentType instanceof WildcardType ) { WildcardType wildcard = ( WildcardType ) componentType ; Type [ ] lowerBounds = wildcard . getLowerBounds ( ) ; checkArgument ( lowerBounds . length <= 1 , "Wildcard cannot have more than one lower bounds." ) ; if ( lowerBounds . length == 1 ) { return supertypeOf ( newArrayType ( lowerBounds [ 0 ] ) ) ; } else { Type [ ] upperBounds = wildcard . getUpperBounds ( ) ; checkArgument ( upperBounds . length == 1 , "Wildcard should have only one upper bound." ) ; return subtypeOf ( newArrayType ( upperBounds [ 0 ] ) ) ; } } return JavaVersion . CURRENT . newArrayType ( componentType ) ;


signature:
public class Types { /** * Returns a type where { @ code rawType } is parameterized by { @ code arguments } . */
static ParameterizedType newParameterizedType ( Class < ? > rawType , Type ... arguments ) { } }

implementation: return new ParameterizedTypeImpl ( ClassOwnership . JVM_BEHAVIOR . getOwnerType ( rawType ) , rawType , arguments ) ;


signature:
public class Types { /** * Returns a new { @ link TypeVariable } that belongs to { @ code declaration } with { @ code name } and
 * { @ code bounds } . */
static < D extends GenericDeclaration > TypeVariable < D > newArtificialTypeVariable ( D declaration , String name , Type ... bounds ) { } }

implementation: return newTypeVariableImpl ( declaration , name , ( bounds . length == 0 ) ? new Type [ ] { Object . class } : bounds ) ;


signature:
public class Types { /** * Returns a new { @ link WildcardType } with { @ code lowerBound } . */
@ VisibleForTesting static WildcardType supertypeOf ( Type lowerBound ) { } }

implementation: return new WildcardTypeImpl ( new Type [ ] { lowerBound } , new Type [ ] { Object . class } ) ;


signature:
public class Tables { /** * Returns a { @ link Collector } that accumulates elements into a { @ code Table } created using the
 * specified supplier , whose cells are generated by applying the provided mapping functions to the
 * input elements . Cells are inserted into the generated { @ code Table } in encounter order .
 * < p > If multiple input elements map to the same row and column , an { @ code IllegalStateException }
 * is thrown when the collection operation is performed .
 * @ since 21.0 */
@ Beta public static < T , R , C , V , I extends Table < R , C , V > > Collector < T , ? , I > toTable ( java . util . function . Function < ? super T , ? extends R > rowFunction , java . util . function . Function < ? super T , ? extends C > columnFunction , java . util . function . Function < ? super T , ? extends V > valueFunction , java . util . function . Supplier < I > tableSupplier ) { } }

implementation: return toTable ( rowFunction , columnFunction , valueFunction , ( v1 , v2 ) -> { throw new IllegalStateException ( "Conflicting values " + v1 + " and " + v2 ) ; } , tableSupplier ) ;


signature:
public class Tables { /** * Returns a { @ link Collector } that accumulates elements into a { @ code Table } created using the
 * specified supplier , whose cells are generated by applying the provided mapping functions to the
 * input elements . Cells are inserted into the generated { @ code Table } in encounter order .
 * < p > If multiple input elements map to the same row and column , the specified merging function is
 * used to combine the values . Like { @ link
 * java . util . stream . Collectors # toMap ( java . util . function . Function , java . util . function . Function ,
 * BinaryOperator , java . util . function . Supplier ) } , this Collector throws a { @ code
 * NullPointerException } on null values returned from { @ code valueFunction } , and treats nulls
 * returned from { @ code mergeFunction } as removals of that row / column pair .
 * @ since 21.0 */
public static < T , R , C , V , I extends Table < R , C , V > > Collector < T , ? , I > toTable ( java . util . function . Function < ? super T , ? extends R > rowFunction , java . util . function . Function < ? super T , ? extends C > columnFunction , java . util . function . Function < ? super T , ? extends V > valueFunction , BinaryOperator < V > mergeFunction , java . util . function . Supplier < I > tableSupplier ) { } }

implementation: checkNotNull ( rowFunction ) ; checkNotNull ( columnFunction ) ; checkNotNull ( valueFunction ) ; checkNotNull ( mergeFunction ) ; checkNotNull ( tableSupplier ) ; return Collector . of ( tableSupplier , ( table , input ) -> merge ( table , rowFunction . apply ( input ) , columnFunction . apply ( input ) , valueFunction . apply ( input ) , mergeFunction ) , ( table1 , table2 ) -> { for ( Table . Cell < R , C , V > cell2 : table2 . cellSet ( ) ) { merge ( table1 , cell2 . getRowKey ( ) , cell2 . getColumnKey ( ) , cell2 . getValue ( ) , mergeFunction ) ; } return table1 ; } ) ;


signature:
public class ImmutableTypeToInstanceMap { /** * Returns an empty type to instance map . */
public static < B > ImmutableTypeToInstanceMap < B > of ( ) { } }

implementation: return new ImmutableTypeToInstanceMap < B > ( ImmutableMap . < TypeToken < ? extends B > , B > of ( ) ) ;


signature:
public class ImmutableTypeToInstanceMap { /** * Guaranteed to throw an exception and leave the map unmodified .
 * @ deprecated unsupported operation
 * @ throws UnsupportedOperationException always */
@ CanIgnoreReturnValue @ Deprecated @ Override public < T extends B > T putInstance ( TypeToken < T > type , T value ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class CycleDetectingLockFactory { /** * Creates a { @ link ReentrantLock } with the given fairness policy . The { @ code lockName } is used in
 * the warning or exception output to help identify the locks involved in the detected deadlock . */
public ReentrantLock newReentrantLock ( String lockName , boolean fair ) { } }

implementation: return policy == Policies . DISABLED ? new ReentrantLock ( fair ) : new CycleDetectingReentrantLock ( new LockGraphNode ( lockName ) , fair ) ;


signature:
public class CycleDetectingLockFactory { /** * Creates a { @ link ReentrantReadWriteLock } with the given fairness policy . The { @ code lockName }
 * is used in the warning or exception output to help identify the locks involved in the detected
 * deadlock . */
public ReentrantReadWriteLock newReentrantReadWriteLock ( String lockName , boolean fair ) { } }

implementation: return policy == Policies . DISABLED ? new ReentrantReadWriteLock ( fair ) : new CycleDetectingReentrantReadWriteLock ( new LockGraphNode ( lockName ) , fair ) ;


signature:
public class CycleDetectingLockFactory { /** * Creates a { @ code CycleDetectingLockFactory . WithExplicitOrdering < E > } . */
public static < E extends Enum < E > > WithExplicitOrdering < E > newInstanceWithExplicitOrdering ( Class < E > enumClass , Policy policy ) { } }

implementation:
// createNodes maps each enumClass to a Map with the corresponding enum key
// type .
checkNotNull ( enumClass ) ; checkNotNull ( policy ) ; @ SuppressWarnings ( "unchecked" ) Map < E , LockGraphNode > lockGraphNodes = ( Map < E , LockGraphNode > ) getOrCreateNodes ( enumClass ) ; return new WithExplicitOrdering < E > ( policy , lockGraphNodes ) ;


signature:
public class CycleDetectingLockFactory { /** * For a given Enum type , creates an immutable map from each of the Enum ' s values to a
 * corresponding LockGraphNode , with the { @ code allowedPriorLocks } and { @ code
 * disallowedPriorLocks } prepopulated with nodes according to the natural ordering of the
 * associated Enum values . */
@ VisibleForTesting static < E extends Enum < E > > Map < E , LockGraphNode > createNodes ( Class < E > clazz ) { } }

implementation:
EnumMap < E , LockGraphNode > map = Maps . newEnumMap ( clazz ) ; E [ ] keys = clazz . getEnumConstants ( ) ; final int numKeys = keys . length ; ArrayList < LockGraphNode > nodes = Lists . newArrayListWithCapacity ( numKeys ) ; // Create a LockGraphNode for each enum value .
for ( E key : keys ) { LockGraphNode node = new LockGraphNode ( getLockName ( key ) ) ; nodes . add ( node ) ; map . put ( key , node ) ; } // Pre - populate all allowedPriorLocks with nodes of smaller ordinal .
for ( int i = 1 ; i < numKeys ; i ++ ) { nodes . get ( i ) . checkAcquiredLocks ( Policies . THROW , nodes . subList ( 0 , i ) ) ; } // Pre - populate all disallowedPriorLocks with nodes of larger ordinal .
for ( int i = 0 ; i < numKeys - 1 ; i ++ ) { nodes . get ( i ) . checkAcquiredLocks ( Policies . DISABLED , nodes . subList ( i + 1 , numKeys ) ) ; } return Collections . unmodifiableMap ( map ) ;


signature:
public class CycleDetectingLockFactory { /** * CycleDetectingLock implementations must call this method before attempting to acquire the lock . */
private void aboutToAcquire ( CycleDetectingLock lock ) { } }

implementation: if ( ! lock . isAcquiredByCurrentThread ( ) ) { ArrayList < LockGraphNode > acquiredLockList = acquiredLocks . get ( ) ; LockGraphNode node = lock . getLockGraphNode ( ) ; node . checkAcquiredLocks ( policy , acquiredLockList ) ; acquiredLockList . add ( node ) ; }


signature:
public class CycleDetectingLockFactory { /** * CycleDetectingLock implementations must call this method in a { @ code finally } clause after any
 * attempt to change the lock state , including both lock and unlock attempts . Failure to do so can
 * result in corrupting the acquireLocks set . */
private static void lockStateChanged ( CycleDetectingLock lock ) { } }

implementation:
if ( ! lock . isAcquiredByCurrentThread ( ) ) { ArrayList < LockGraphNode > acquiredLockList = acquiredLocks . get ( ) ; LockGraphNode node = lock . getLockGraphNode ( ) ; // Iterate in reverse because locks are usually locked / unlocked in a
// LIFO order .
for ( int i = acquiredLockList . size ( ) - 1 ; i >= 0 ; i -- ) { if ( acquiredLockList . get ( i ) == node ) { acquiredLockList . remove ( i ) ; break ; } } }


signature:
public class CollectSpliterators { /** * Returns a { @ code Spliterator } over the elements of { @ code fromSpliterator } mapped by { @ code
 * function } . */
static < F , T > Spliterator < T > map ( Spliterator < F > fromSpliterator , Function < ? super F , ? extends T > function ) { } }

implementation: checkNotNull ( fromSpliterator ) ; checkNotNull ( function ) ; return new Spliterator < T > ( ) { @ Override public boolean tryAdvance ( Consumer < ? super T > action ) { return fromSpliterator . tryAdvance ( fromElement -> action . accept ( function . apply ( fromElement ) ) ) ; } @ Override public void forEachRemaining ( Consumer < ? super T > action ) { fromSpliterator . forEachRemaining ( fromElement -> action . accept ( function . apply ( fromElement ) ) ) ; } @ Override public Spliterator < T > trySplit ( ) { Spliterator < F > fromSplit = fromSpliterator . trySplit ( ) ; return ( fromSplit != null ) ? map ( fromSplit , function ) : null ; } @ Override public long estimateSize ( ) { return fromSpliterator . estimateSize ( ) ; } @ Override public int characteristics ( ) { return fromSpliterator . characteristics ( ) & ~ ( Spliterator . DISTINCT | Spliterator . NONNULL | Spliterator . SORTED ) ; } } ;


signature:
public class CollectSpliterators { /** * Returns a { @ code Spliterator } filtered by the specified predicate . */
static < T > Spliterator < T > filter ( Spliterator < T > fromSpliterator , Predicate < ? super T > predicate ) { } }

implementation: checkNotNull ( fromSpliterator ) ; checkNotNull ( predicate ) ; class Splitr implements Spliterator < T > , Consumer < T > { T holder = null ; @ Override public void accept ( T t ) { this . holder = t ; } @ Override public boolean tryAdvance ( Consumer < ? super T > action ) { while ( fromSpliterator . tryAdvance ( this ) ) { try { if ( predicate . test ( holder ) ) { action . accept ( holder ) ; return true ; } } finally { holder = null ; } } return false ; } @ Override public Spliterator < T > trySplit ( ) { Spliterator < T > fromSplit = fromSpliterator . trySplit ( ) ; return ( fromSplit == null ) ? null : filter ( fromSplit , predicate ) ; } @ Override public long estimateSize ( ) { return fromSpliterator . estimateSize ( ) / 2 ; } @ Override public Comparator < ? super T > getComparator ( ) { return fromSpliterator . getComparator ( ) ; } @ Override public int characteristics ( ) { return fromSpliterator . characteristics ( ) & ( Spliterator . DISTINCT | Spliterator . NONNULL | Spliterator . ORDERED | Spliterator . SORTED ) ; } } return new Splitr ( ) ;


signature:
public class CollectSpliterators { /** * Returns a { @ code Spliterator } that iterates over the elements of the spliterators generated by
 * applying { @ code function } to the elements of { @ code fromSpliterator } . */
static < F , T > Spliterator < T > flatMap ( Spliterator < F > fromSpliterator , Function < ? super F , Spliterator < T > > function , int topCharacteristics , long topSize ) { } }

implementation: checkArgument ( ( topCharacteristics & Spliterator . SUBSIZED ) == 0 , "flatMap does not support SUBSIZED characteristic" ) ; checkArgument ( ( topCharacteristics & Spliterator . SORTED ) == 0 , "flatMap does not support SORTED characteristic" ) ; checkNotNull ( fromSpliterator ) ; checkNotNull ( function ) ; class FlatMapSpliterator implements Spliterator < T > { @ Nullable Spliterator < T > prefix ; final Spliterator < F > from ; int characteristics ; long estimatedSize ; FlatMapSpliterator ( Spliterator < T > prefix , Spliterator < F > from , int characteristics , long estimatedSize ) { this . prefix = prefix ; this . from = from ; this . characteristics = characteristics ; this . estimatedSize = estimatedSize ; } @ Override public boolean tryAdvance ( Consumer < ? super T > action ) { while ( true ) { if ( prefix != null && prefix . tryAdvance ( action ) ) { if ( estimatedSize != Long . MAX_VALUE ) { estimatedSize -- ; } return true ; } else { prefix = null ; } if ( ! from . tryAdvance ( fromElement -> prefix = function . apply ( fromElement ) ) ) { return false ; } } } @ Override public void forEachRemaining ( Consumer < ? super T > action ) { if ( prefix != null ) { prefix . forEachRemaining ( action ) ; prefix = null ; } from . forEachRemaining ( fromElement -> function . apply ( fromElement ) . forEachRemaining ( action ) ) ; estimatedSize = 0 ; } @ Override public Spliterator < T > trySplit ( ) { Spliterator < F > fromSplit = from . trySplit ( ) ; if ( fromSplit != null ) { int splitCharacteristics = characteristics & ~ Spliterator . SIZED ; long estSplitSize = estimateSize ( ) ; if ( estSplitSize < Long . MAX_VALUE ) { estSplitSize /= 2 ; this . estimatedSize -= estSplitSize ; this . characteristics = splitCharacteristics ; } Spliterator < T > result = new FlatMapSpliterator ( this . prefix , fromSplit , splitCharacteristics , estSplitSize ) ; this . prefix = null ; return result ; } else if ( prefix != null ) { Spliterator < T > result = prefix ; this . prefix = null ; return result ; } else { return null ; } } @ Override public long estimateSize ( ) { if ( prefix != null ) { estimatedSize = Math . max ( estimatedSize , prefix . estimateSize ( ) ) ; } return Math . max ( estimatedSize , 0 ) ; } @ Override public int characteristics ( ) { return characteristics ; } } return new FlatMapSpliterator ( null , fromSpliterator , topCharacteristics , topSize ) ;


signature:
public class LinearTransformation { /** * Start building an instance which maps { @ code x = x1 } to { @ code y = y1 } . Both arguments must be
 * finite . Call either { @ link LinearTransformationBuilder # and } or { @ link
 * LinearTransformationBuilder # withSlope } on the returned object to finish building the instance . */
public static LinearTransformationBuilder mapping ( double x1 , double y1 ) { } }

implementation: checkArgument ( isFinite ( x1 ) && isFinite ( y1 ) ) ; return new LinearTransformationBuilder ( x1 , y1 ) ;


signature:
public class LinearTransformation { /** * Builds an instance representing a horizontal transformation with a constant value of { @ code y } .
 * ( The inverse of this will be a vertical transformation . ) */
public static LinearTransformation horizontal ( double y ) { } }

implementation: checkArgument ( isFinite ( y ) ) ; double slope = 0.0 ; return new RegularLinearTransformation ( slope , y ) ;


signature:
public class ImmutableTable { /** * Returns a { @ code Collector } that accumulates elements into an { @ code ImmutableTable } . Each
 * input element is mapped to one cell in the returned table , with the rows , columns , and values
 * generated by applying the specified functions .
 * < p > The returned { @ code Collector } will throw a { @ code NullPointerException } at collection time
 * if the row , column , or value functions return null on any input .
 * @ since 21.0 */
public static < T , R , C , V > Collector < T , ? , ImmutableTable < R , C , V > > toImmutableTable ( Function < ? super T , ? extends R > rowFunction , Function < ? super T , ? extends C > columnFunction , Function < ? super T , ? extends V > valueFunction ) { } }

implementation: checkNotNull ( rowFunction , "rowFunction" ) ; checkNotNull ( columnFunction , "columnFunction" ) ; checkNotNull ( valueFunction , "valueFunction" ) ; return Collector . of ( ( ) -> new ImmutableTable . Builder < R , C , V > ( ) , ( builder , t ) -> builder . put ( rowFunction . apply ( t ) , columnFunction . apply ( t ) , valueFunction . apply ( t ) ) , ( b1 , b2 ) -> b1 . combine ( b2 ) , b -> b . build ( ) ) ;


signature:
public class ImmutableTable { /** * Returns a { @ code Collector } that accumulates elements into an { @ code ImmutableTable } . Each
 * input element is mapped to one cell in the returned table , with the rows , columns , and values
 * generated by applying the specified functions . If multiple inputs are mapped to the same row
 * and column pair , they will be combined with the specified merging function in encounter order .
 * < p > The returned { @ code Collector } will throw a { @ code NullPointerException } at collection time
 * if the row , column , value , or merging functions return null on any input .
 * @ since 21.0 */
public static < T , R , C , V > Collector < T , ? , ImmutableTable < R , C , V > > toImmutableTable ( Function < ? super T , ? extends R > rowFunction , Function < ? super T , ? extends C > columnFunction , Function < ? super T , ? extends V > valueFunction , BinaryOperator < V > mergeFunction ) { } }

implementation:
checkNotNull ( rowFunction , "rowFunction" ) ; checkNotNull ( columnFunction , "columnFunction" ) ; checkNotNull ( valueFunction , "valueFunction" ) ; checkNotNull ( mergeFunction , "mergeFunction" ) ; /* * No mutable Table exactly matches the insertion order behavior of ImmutableTable . Builder , but
 * the Builder can ' t efficiently support merging of duplicate values . Getting around this
 * requires some work . */
return Collector . of ( ( ) -> new CollectorState < R , C , V > ( ) /* GWT isn ' t currently playing nicely with constructor references ? */
, ( state , input ) -> state . put ( rowFunction . apply ( input ) , columnFunction . apply ( input ) , valueFunction . apply ( input ) , mergeFunction ) , ( s1 , s2 ) -> s1 . combine ( s2 , mergeFunction ) , state -> state . toTable ( ) ) ;


signature:
public class ImmutableRangeSet { /** * Returns an immutable range set containing the specified single range . If { @ link Range # isEmpty ( )
 * range . isEmpty ( ) } , this is equivalent to { @ link ImmutableRangeSet # of ( ) } . */
public static < C extends Comparable > ImmutableRangeSet < C > of ( Range < C > range ) { } }

implementation: checkNotNull ( range ) ; if ( range . isEmpty ( ) ) { return of ( ) ; } else if ( range . equals ( Range . all ( ) ) ) { return all ( ) ; } else { return new ImmutableRangeSet < C > ( ImmutableList . of ( range ) ) ; }


signature:
public class ImmutableRangeSet { /** * Returns an immutable copy of the specified { @ code RangeSet } . */
public static < C extends Comparable > ImmutableRangeSet < C > copyOf ( RangeSet < C > rangeSet ) { } }

implementation: checkNotNull ( rangeSet ) ; if ( rangeSet . isEmpty ( ) ) { return of ( ) ; } else if ( rangeSet . encloses ( Range . < C > all ( ) ) ) { return all ( ) ; } if ( rangeSet instanceof ImmutableRangeSet ) { ImmutableRangeSet < C > immutableRangeSet = ( ImmutableRangeSet < C > ) rangeSet ; if ( ! immutableRangeSet . isPartialView ( ) ) { return immutableRangeSet ; } } return new ImmutableRangeSet < C > ( ImmutableList . copyOf ( rangeSet . asRanges ( ) ) ) ;


signature:
public class ImmutableRangeSet { /** * Returns an { @ code ImmutableRangeSet } containing each of the specified disjoint ranges .
 * Overlapping ranges and empty ranges are forbidden , though adjacent ranges are permitted and
 * will be merged .
 * @ throws IllegalArgumentException if any ranges overlap or are empty
 * @ since 21.0 */
public static < C extends Comparable < ? > > ImmutableRangeSet < C > copyOf ( Iterable < Range < C > > ranges ) { } }

implementation: return new ImmutableRangeSet . Builder < C > ( ) . addAll ( ranges ) . build ( ) ;


signature:
public class ImmutableRangeSet { /** * Returns an { @ code ImmutableRangeSet } representing the union of the specified ranges .
 * < p > This is the smallest { @ code RangeSet } which encloses each of the specified ranges . Duplicate
 * or connected ranges are permitted , and will be coalesced in the result .
 * @ since 21.0 */
public static < C extends Comparable < ? > > ImmutableRangeSet < C > unionOf ( Iterable < Range < C > > ranges ) { } }

implementation: return copyOf ( TreeRangeSet . create ( ranges ) ) ;


signature:
public class ImmutableRangeSet { /** * Returns a new range set consisting of the union of this range set and { @ code other } .
 * < p > This is essentially the same as { @ code TreeRangeSet . create ( this ) . addAll ( other ) } except it
 * returns an { @ code ImmutableRangeSet } .
 * @ since 21.0 */
public ImmutableRangeSet < C > union ( RangeSet < C > other ) { } }

implementation: return unionOf ( Iterables . concat ( asRanges ( ) , other . asRanges ( ) ) ) ;


signature:
public class ImmutableRangeSet { /** * Returns a new range set consisting of the intersection of this range set and { @ code other } .
 * < p > This is essentially the same as { @ code
 * TreeRangeSet . create ( this ) . removeAll ( other . complement ( ) ) } except it returns an { @ code
 * ImmutableRangeSet } .
 * @ since 21.0 */
public ImmutableRangeSet < C > intersection ( RangeSet < C > other ) { } }

implementation: RangeSet < C > copy = TreeRangeSet . create ( this ) ; copy . removeAll ( other . complement ( ) ) ; return copyOf ( copy ) ;


signature:
public class ImmutableRangeSet { /** * Returns a new range set consisting of the difference of this range set and { @ code other } .
 * < p > This is essentially the same as { @ code TreeRangeSet . create ( this ) . removeAll ( other ) } except it
 * returns an { @ code ImmutableRangeSet } .
 * @ since 21.0 */
public ImmutableRangeSet < C > difference ( RangeSet < C > other ) { } }

implementation: RangeSet < C > copy = TreeRangeSet . create ( this ) ; copy . removeAll ( other ) ; return copyOf ( copy ) ;


signature:
public class ImmutableRangeSet { /** * Returns a list containing the nonempty intersections of { @ code range } with the ranges in this
 * range set . */
private ImmutableList < Range < C > > intersectRanges ( final Range < C > range ) { } }

implementation: if ( ranges . isEmpty ( ) || range . isEmpty ( ) ) { return ImmutableList . of ( ) ; } else if ( range . encloses ( span ( ) ) ) { return ranges ; } final int fromIndex ; if ( range . hasLowerBound ( ) ) { fromIndex = SortedLists . binarySearch ( ranges , Range . < C > upperBoundFn ( ) , range . lowerBound , KeyPresentBehavior . FIRST_AFTER , KeyAbsentBehavior . NEXT_HIGHER ) ; } else { fromIndex = 0 ; } int toIndex ; if ( range . hasUpperBound ( ) ) { toIndex = SortedLists . binarySearch ( ranges , Range . < C > lowerBoundFn ( ) , range . upperBound , KeyPresentBehavior . FIRST_PRESENT , KeyAbsentBehavior . NEXT_HIGHER ) ; } else { toIndex = ranges . size ( ) ; } final int length = toIndex - fromIndex ; if ( length == 0 ) { return ImmutableList . of ( ) ; } else { return new ImmutableList < Range < C > > ( ) { @ Override public int size ( ) { return length ; } @ Override public Range < C > get ( int index ) { checkElementIndex ( index , length ) ; if ( index == 0 || index == length - 1 ) { return ranges . get ( index + fromIndex ) . intersection ( range ) ; } else { return ranges . get ( index + fromIndex ) ; } } @ Override boolean isPartialView ( ) { return true ; } } ; }


signature:
public class ImmutableRangeSet { /** * Returns a view of the intersection of this range set with the given range . */
@ Override public ImmutableRangeSet < C > subRangeSet ( Range < C > range ) { } }

implementation: if ( ! isEmpty ( ) ) { Range < C > span = span ( ) ; if ( range . encloses ( span ) ) { return this ; } else if ( range . isConnected ( span ) ) { return new ImmutableRangeSet < C > ( intersectRanges ( range ) ) ; } } return of ( ) ;


signature:
public class ImmutableRangeSet { /** * Returns an { @ link ImmutableSortedSet } containing the same values in the given domain
 * { @ linkplain RangeSet # contains contained } by this range set .
 * < p > < b > Note : < / b > { @ code a . asSet ( d ) . equals ( b . asSet ( d ) ) } does not imply { @ code a . equals ( b ) } ! For
 * example , { @ code a } and { @ code b } could be { @ code [ 2 . . 4 ] } and { @ code ( 1 . . 5 ) } , or the empty
 * ranges { @ code [ 3 . . 3 ) } and { @ code [ 4 . . 4 ) } .
 * < p > < b > Warning : < / b > Be extremely careful what you do with the { @ code asSet } view of a large
 * range set ( such as { @ code ImmutableRangeSet . of ( Range . greaterThan ( 0 ) ) } ) . Certain operations on
 * such a set can be performed efficiently , but others ( such as { @ link Set # hashCode } or { @ link
 * Collections # frequency } ) can cause major performance problems .
 * < p > The returned set ' s { @ link Object # toString } method returns a short - hand form of the set ' s
 * contents , such as { @ code " [ 1 . . 100 ] } " } .
 * @ throws IllegalArgumentException if neither this range nor the domain has a lower bound , or if
 * neither has an upper bound */
public ImmutableSortedSet < C > asSet ( DiscreteDomain < C > domain ) { } }

implementation:
checkNotNull ( domain ) ; if ( isEmpty ( ) ) { return ImmutableSortedSet . of ( ) ; } Range < C > span = span ( ) . canonical ( domain ) ; if ( ! span . hasLowerBound ( ) ) { // according to the spec of canonical , neither this ImmutableRangeSet nor
// the range have a lower bound
throw new IllegalArgumentException ( "Neither the DiscreteDomain nor this range set are bounded below" ) ; } else if ( ! span . hasUpperBound ( ) ) { try { domain . maxValue ( ) ; } catch ( NoSuchElementException e ) { throw new IllegalArgumentException ( "Neither the DiscreteDomain nor this range set are bounded above" ) ; } } return new AsSet ( domain ) ;


signature:
public class Uninterruptibles { /** * Invokes { @ code condition . } { @ link Condition # await ( long , TimeUnit ) await ( timeout , unit ) }
 * uninterruptibly .
 * @ since 23.6 */
@ GwtIncompatible // concurrency
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static boolean awaitUninterruptibly ( Condition condition , long timeout , TimeUnit unit ) { } }

implementation: boolean interrupted = false ; try { long remainingNanos = unit . toNanos ( timeout ) ; long end = System . nanoTime ( ) + remainingNanos ; while ( true ) { try { return condition . await ( remainingNanos , NANOSECONDS ) ; } catch ( InterruptedException e ) { interrupted = true ; remainingNanos = end - System . nanoTime ( ) ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } }


signature:
public class Uninterruptibles { /** * Invokes { @ code toJoin . } { @ link Thread # join ( ) join ( ) } uninterruptibly . */
@ GwtIncompatible // concurrency
public static void joinUninterruptibly ( Thread toJoin ) { } }

implementation: boolean interrupted = false ; try { while ( true ) { try { toJoin . join ( ) ; return ; } catch ( InterruptedException e ) { interrupted = true ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } }


signature:
public class Uninterruptibles { /** * Invokes { @ code future . } { @ link Future # get ( ) get ( ) } uninterruptibly .
 * < p > Similar methods :
 * < ul >
 * < li > To retrieve a result from a { @ code Future } that is already done , use { @ link
 * Futures # getDone Futures . getDone } .
 * < li > To treat { @ link InterruptedException } uniformly with other exceptions , use { @ link
 * Futures # getChecked ( Future , Class ) Futures . getChecked } .
 * < li > To get uninterruptibility and remove checked exceptions , use { @ link
 * Futures # getUnchecked } .
 * < / ul >
 * @ throws ExecutionException if the computation threw an exception
 * @ throws CancellationException if the computation was cancelled */
@ CanIgnoreReturnValue public static < V > V getUninterruptibly ( Future < V > future ) throws ExecutionException { } }

implementation: boolean interrupted = false ; try { while ( true ) { try { return future . get ( ) ; } catch ( InterruptedException e ) { interrupted = true ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } }


signature:
public class Uninterruptibles { /** * Invokes { @ code semaphore . } { @ link Semaphore # tryAcquire ( int , long , TimeUnit ) tryAcquire ( 1,
 * timeout , unit ) } uninterruptibly .
 * @ since 18.0 */
@ GwtIncompatible // concurrency
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static boolean tryAcquireUninterruptibly ( Semaphore semaphore , long timeout , TimeUnit unit ) { } }

implementation: return tryAcquireUninterruptibly ( semaphore , 1 , timeout , unit ) ;


signature:
public class Uninterruptibles { /** * Invokes { @ code semaphore . } { @ link Semaphore # tryAcquire ( int , long , TimeUnit ) tryAcquire ( permits ,
 * timeout , unit ) } uninterruptibly .
 * @ since 18.0 */
@ GwtIncompatible // concurrency
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static boolean tryAcquireUninterruptibly ( Semaphore semaphore , int permits , long timeout , TimeUnit unit ) { } }

implementation:
boolean interrupted = false ; try { long remainingNanos = unit . toNanos ( timeout ) ; long end = System . nanoTime ( ) + remainingNanos ; while ( true ) { try { // Semaphore treats negative timeouts just like zero .
return semaphore . tryAcquire ( permits , remainingNanos , NANOSECONDS ) ; } catch ( InterruptedException e ) { interrupted = true ; remainingNanos = end - System . nanoTime ( ) ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } }


signature:
public class CacheBuilderSpec { /** * Converts an expiration duration / unit pair into a single Long for hashing and equality . Uses
 * nanos to match CacheBuilder implementation . */
private static @ Nullable Long durationInNanos ( long duration , @ Nullable TimeUnit unit ) { } }

implementation: return ( unit == null ) ? null : unit . toNanos ( duration ) ;


signature:
public class UnsignedLongs { /** * Returns the unsigned { @ code long } value represented by the given string .
 * < p > Accepts a decimal , hexadecimal , or octal number given by specifying the following prefix :
 * < ul >
 * < li > { @ code 0x } < i > HexDigits < / i >
 * < li > { @ code 0X } < i > HexDigits < / i >
 * < li > { @ code # } < i > HexDigits < / i >
 * < li > { @ code 0 } < i > OctalDigits < / i >
 * < / ul >
 * @ throws NumberFormatException if the string does not contain a valid unsigned { @ code long }
 * value
 * @ since 13.0 */
@ CanIgnoreReturnValue public static long decode ( String stringValue ) { } }

implementation: ParseRequest request = ParseRequest . fromString ( stringValue ) ; try { return parseUnsignedLong ( request . rawValue , request . radix ) ; } catch ( NumberFormatException e ) { NumberFormatException decodeException = new NumberFormatException ( "Error parsing value: " + stringValue ) ; decodeException . initCause ( e ) ; throw decodeException ; }


signature:
public class RegularImmutableMap { /** * Creates an ImmutableMap from the first n entries in entryArray . This implementation may replace
 * the entries in entryArray with its own entry objects ( though they will have the same key / value
 * contents ) , and may take ownership of entryArray . */
static < K , V > ImmutableMap < K , V > fromEntryArray ( int n , Entry < K , V > [ ] entryArray ) { } }

implementation:
checkPositionIndex ( n , entryArray . length ) ; if ( n == 0 ) { return ( RegularImmutableMap < K , V > ) EMPTY ; } Entry < K , V > [ ] entries ; if ( n == entryArray . length ) { entries = entryArray ; } else { entries = createEntryArray ( n ) ; } int tableSize = Hashing . closedTableSize ( n , MAX_LOAD_FACTOR ) ; ImmutableMapEntry < K , V > [ ] table = createEntryArray ( tableSize ) ; int mask = tableSize - 1 ; for ( int entryIndex = 0 ; entryIndex < n ; entryIndex ++ ) { Entry < K , V > entry = entryArray [ entryIndex ] ; K key = entry . getKey ( ) ; V value = entry . getValue ( ) ; checkEntryNotNull ( key , value ) ; int tableIndex = Hashing . smear ( key . hashCode ( ) ) & mask ; @ Nullable ImmutableMapEntry < K , V > existing = table [ tableIndex ] ; // prepend , not append , so the entries can be immutable
ImmutableMapEntry < K , V > newEntry = ( existing == null ) ? makeImmutable ( entry , key , value ) : new NonTerminalImmutableMapEntry < K , V > ( key , value , existing ) ; table [ tableIndex ] = newEntry ; entries [ entryIndex ] = newEntry ; int bucketSize = checkNoConflictInKeyBucket ( key , newEntry , existing ) ; if ( bucketSize > MAX_HASH_BUCKET_LENGTH ) { // probable hash flooding attack , fall back to j . u . HM based implementation and use its
// implementation of hash flooding protection
return JdkBackedImmutableMap . create ( n , entryArray ) ; } } return new RegularImmutableMap < > ( entries , table , mask ) ;


signature:
public class RegularImmutableMap { /** * Makes an entry usable internally by a new ImmutableMap without rereading its contents . */
static < K , V > ImmutableMapEntry < K , V > makeImmutable ( Entry < K , V > entry , K key , V value ) { } }

implementation: boolean reusable = entry instanceof ImmutableMapEntry && ( ( ImmutableMapEntry < K , V > ) entry ) . isReusable ( ) ; return reusable ? ( ImmutableMapEntry < K , V > ) entry : new ImmutableMapEntry < K , V > ( key , value ) ;


signature:
public class RegularImmutableMap { /** * Makes an entry usable internally by a new ImmutableMap . */
static < K , V > ImmutableMapEntry < K , V > makeImmutable ( Entry < K , V > entry ) { } }

implementation: return makeImmutable ( entry , entry . getKey ( ) , entry . getValue ( ) ) ;


signature:
public class ImmutableMultiset { /** * Returns a { @ code Collector } that accumulates the input elements into a new { @ code
 * ImmutableMultiset } . Elements iterate in order by the < i > first < / i > appearance of that element in
 * encounter order .
 * @ since 21.0 */
public static < E > Collector < E , ? , ImmutableMultiset < E > > toImmutableMultiset ( ) { } }

implementation: return toImmutableMultiset ( Function . identity ( ) , e -> 1 ) ;


signature:
public class ImmutableMultiset { /** * Returns a { @ code Collector } that accumulates elements into an { @ code ImmutableMultiset } whose
 * elements are the result of applying { @ code elementFunction } to the inputs , with counts equal to
 * the result of applying { @ code countFunction } to the inputs .
 * < p > If the mapped elements contain duplicates ( according to { @ link Object # equals } ) , the first
 * occurrence in encounter order appears in the resulting multiset , with count equal to the sum of
 * the outputs of { @ code countFunction . applyAsInt ( t ) } for each { @ code t } mapped to that element .
 * @ since 22.0 */
public static < T , E > Collector < T , ? , ImmutableMultiset < E > > toImmutableMultiset ( Function < ? super T , ? extends E > elementFunction , ToIntFunction < ? super T > countFunction ) { } }

implementation: checkNotNull ( elementFunction ) ; checkNotNull ( countFunction ) ; return Collector . of ( LinkedHashMultiset :: create , ( multiset , t ) -> multiset . add ( checkNotNull ( elementFunction . apply ( t ) ) , countFunction . applyAsInt ( t ) ) , ( multiset1 , multiset2 ) -> { multiset1 . addAll ( multiset2 ) ; return multiset1 ; } , ( Multiset < E > multiset ) -> copyFromEntries ( multiset . entrySet ( ) ) ) ;


signature:
public class ImmutableMultiset { /** * Returns an immutable multiset containing the given elements , in the " grouped iteration order "
 * described in the class documentation .
 * @ throws NullPointerException if any element is null
 * @ since 6.0 ( source - compatible since 2.0) */
@ SuppressWarnings ( "unchecked" ) public static < E > ImmutableMultiset < E > of ( E e1 , E e2 , E e3 , E e4 , E e5 , E e6 , E ... others ) { } }

implementation: return new Builder < E > ( ) . add ( e1 ) . add ( e2 ) . add ( e3 ) . add ( e4 ) . add ( e5 ) . add ( e6 ) . add ( others ) . build ( ) ;


signature:
public class ImmutableMultiset { /** * Returns an immutable multiset containing the given elements , in the " grouped iteration order "
 * described in the class documentation .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableMultiset < E > copyOf ( Iterable < ? extends E > elements ) { } }

implementation:
if ( elements instanceof ImmutableMultiset ) { @ SuppressWarnings ( "unchecked" ) // all supported methods are covariant
ImmutableMultiset < E > result = ( ImmutableMultiset < E > ) elements ; if ( ! result . isPartialView ( ) ) { return result ; } } Multiset < ? extends E > multiset = ( elements instanceof Multiset ) ? Multisets . cast ( elements ) : LinkedHashMultiset . create ( elements ) ; return copyFromEntries ( multiset . entrySet ( ) ) ;


signature:
public class ImmutableMultiset { /** * Returns an immutable multiset containing the given elements , in the " grouped iteration order "
 * described in the class documentation .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableMultiset < E > copyOf ( Iterator < ? extends E > elements ) { } }

implementation: Multiset < E > multiset = LinkedHashMultiset . create ( ) ; Iterators . addAll ( multiset , elements ) ; return copyFromEntries ( multiset . entrySet ( ) ) ;


signature:
public class Graphs { /** * Determines whether an edge has already been used during traversal . In the directed case a cycle
 * is always detected before reusing an edge , so no special logic is required . In the undirected
 * case , we must take care not to " backtrack " over an edge ( i . e . going from A to B and then going
 * from B to A ) . */
private static boolean canTraverseWithoutReusingEdge ( Graph < ? > graph , Object nextNode , @ Nullable Object previousNode ) { } }

implementation:
if ( graph . isDirected ( ) || ! Objects . equal ( previousNode , nextNode ) ) { return true ; } // This falls into the undirected A - > B - > A case . The Graph interface does not support parallel
// edges , so this traversal would require reusing the undirected AB edge .
return false ;


signature:
public class Escapers { /** * Returns a { @ link UnicodeEscaper } equivalent to the given escaper instance . If the escaper is
 * already a UnicodeEscaper then it is simply returned , otherwise it is wrapped in a
 * UnicodeEscaper .
 * < p > When a { @ link CharEscaper } escaper is wrapped by this method it acquires extra behavior with
 * respect to the well - formedness of Unicode character sequences and will throw { @ link
 * IllegalArgumentException } when given bad input .
 * @ param escaper the instance to be wrapped
 * @ return a UnicodeEscaper with the same behavior as the given instance
 * @ throws NullPointerException if escaper is null
 * @ throws IllegalArgumentException if escaper is not a UnicodeEscaper or a CharEscaper */
static UnicodeEscaper asUnicodeEscaper ( Escaper escaper ) { } }

implementation:
checkNotNull ( escaper ) ; if ( escaper instanceof UnicodeEscaper ) { return ( UnicodeEscaper ) escaper ; } else if ( escaper instanceof CharEscaper ) { return wrap ( ( CharEscaper ) escaper ) ; } // In practice this shouldn ' t happen because it would be very odd not to
// extend either CharEscaper or UnicodeEscaper for non trivial cases .
throw new IllegalArgumentException ( "Cannot create a UnicodeEscaper from: " + escaper . getClass ( ) . getName ( ) ) ;


signature:
public class Escapers { /** * Private helper to wrap a CharEscaper as a UnicodeEscaper . */
private static UnicodeEscaper wrap ( final CharEscaper escaper ) { } }

implementation:
return new UnicodeEscaper ( ) { @ Override protected char [ ] escape ( int cp ) { // If a code point maps to a single character , just escape that .
if ( cp < Character . MIN_SUPPLEMENTARY_CODE_POINT ) { return escaper . escape ( ( char ) cp ) ; } // Convert the code point to a surrogate pair and escape them both .
// Note : This code path is horribly slow and typically allocates 4 new
// char [ ] each time it is invoked . However this avoids any
// synchronization issues and makes the escaper thread safe .
char [ ] surrogateChars = new char [ 2 ] ; Character . toChars ( cp , surrogateChars , 0 ) ; char [ ] hiChars = escaper . escape ( surrogateChars [ 0 ] ) ; char [ ] loChars = escaper . escape ( surrogateChars [ 1 ] ) ; // If either hiChars or lowChars are non - null , the CharEscaper is trying
// to escape the characters of a surrogate pair separately . This is
// uncommon and applies only to escapers that assume UCS - 2 rather than
// UTF - 16 . See : http : / / en . wikipedia . org / wiki / UTF - 16 / UCS - 2
if ( hiChars == null && loChars == null ) { // We expect this to be the common code path for most escapers .
return null ; } // Combine the characters and / or escaped sequences into a single array .
int hiCount = hiChars != null ? hiChars . length : 1 ; int loCount = loChars != null ? loChars . length : 1 ; char [ ] output = new char [ hiCount + loCount ] ; if ( hiChars != null ) { // TODO : Is this faster than System . arraycopy ( ) for small arrays ?
for ( int n = 0 ; n < hiChars . length ; ++ n ) { output [ n ] = hiChars [ n ] ; } } else { output [ 0 ] = surrogateChars [ 0 ] ; } if ( loChars != null ) { for ( int n = 0 ; n < loChars . length ; ++ n ) { output [ hiCount + n ] = loChars [ n ] ; } } else { output [ hiCount ] = surrogateChars [ 1 ] ; } return output ; } } ;


signature:
public class AbstractMapBasedMultiset { /** * { @ inheritDoc }
 * @ throws IllegalArgumentException if the call would result in more than { @ link
 * Integer # MAX _ VALUE } occurrences of { @ code element } in this multiset . */
@ CanIgnoreReturnValue @ Override public final int add ( @ NullableDecl E element , int occurrences ) { } }

implementation: if ( occurrences == 0 ) { return count ( element ) ; } checkArgument ( occurrences > 0 , "occurrences cannot be negative: %s" , occurrences ) ; int entryIndex = backingMap . indexOf ( element ) ; if ( entryIndex == - 1 ) { backingMap . put ( element , occurrences ) ; size += occurrences ; return 0 ; } int oldCount = backingMap . getValue ( entryIndex ) ; long newCount = ( long ) oldCount + ( long ) occurrences ; checkArgument ( newCount <= Integer . MAX_VALUE , "too many occurrences: %s" , newCount ) ; backingMap . setValue ( entryIndex , ( int ) newCount ) ; size += occurrences ; return oldCount ;


signature:
public class AbstractMapBasedMultiset { /** * Allocation - free implementation of { @ code target . addAll ( this ) } . */
void addTo ( Multiset < ? super E > target ) { } }

implementation: checkNotNull ( target ) ; for ( int i = backingMap . firstIndex ( ) ; i >= 0 ; i = backingMap . nextIndex ( i ) ) { target . add ( backingMap . getKey ( i ) , backingMap . getValue ( i ) ) ; }


signature:
public class TypeToken { /** * Returns the array component type if this type represents an array ( { @ code int [ ] } , { @ code T [ ] } ,
 * { @ code < ? extends Map < String , Integer > [ ] > } etc . ) , or else { @ code null } is returned . */
@ NullableDecl public final TypeToken < ? > getComponentType ( ) { } }

implementation: Type componentType = Types . getComponentType ( runtimeType ) ; if ( componentType == null ) { return null ; } return of ( componentType ) ;


signature:
public class TypeToken { /** * Returns the owner type of a { @ link ParameterizedType } or enclosing class of a { @ link Class } , or
 * null otherwise . */
@ NullableDecl private Type getOwnerTypeIfPresent ( ) { } }

implementation: if ( runtimeType instanceof ParameterizedType ) { return ( ( ParameterizedType ) runtimeType ) . getOwnerType ( ) ; } else if ( runtimeType instanceof Class < ? > ) { return ( ( Class < ? > ) runtimeType ) . getEnclosingClass ( ) ; } else { return null ; }


signature:
public class PairedStatsAccumulator { /** * Adds the given pair of values to the dataset . */
public void add ( double x , double y ) { } }

implementation:
// We extend the recursive expression for the one - variable case at Art of Computer Programming
// vol . 2 , Knuth , 4.2.2 , ( 16 ) to the two - variable case . We have two value series x _ i and y _ i .
// We define the arithmetic means X _ n = 1 / n \ sum _ { i = 1 } ^ n x _ i , and Y _ n = 1 / n \ sum _ { i = 1 } ^ n y _ i .
// We also define the sum of the products of the differences from the means
// C _ n = \ sum _ { i = 1 } ^ n x _ i y _ i - n X _ n Y _ n
// for all n > = 1 . Then for all n > 1:
// C _ { n - 1 } = \ sum _ { i = 1 } ^ { n - 1 } x _ i y _ i - ( n - 1 ) X _ { n - 1 } Y _ { n - 1}
// C _ n - C _ { n - 1 } = x _ n y _ n - n X _ n Y _ n + ( n - 1 ) X _ { n - 1 } Y _ { n - 1}
// = x _ n y _ n - X _ n [ y _ n + ( n - 1 ) Y _ { n - 1 } ] + [ n X _ n - x _ n ] Y _ { n - 1}
// = x _ n y _ n - X _ n y _ n - x _ n Y _ { n - 1 } + X _ n Y _ { n - 1}
// = ( x _ n - X _ n ) ( y _ n - Y _ { n - 1 } )
xStats . add ( x ) ; if ( isFinite ( x ) && isFinite ( y ) ) { if ( xStats . count ( ) > 1 ) { sumOfProductsOfDeltas += ( x - xStats . mean ( ) ) * ( y - yStats . mean ( ) ) ; } } else { sumOfProductsOfDeltas = NaN ; } yStats . add ( y ) ;


signature:
public class PairedStatsAccumulator { /** * Adds the given statistics to the dataset , as if the individual values used to compute the
 * statistics had been added directly . */
public void addAll ( PairedStats values ) { } }

implementation:
if ( values . count ( ) == 0 ) { return ; } xStats . addAll ( values . xStats ( ) ) ; if ( yStats . count ( ) == 0 ) { sumOfProductsOfDeltas = values . sumOfProductsOfDeltas ( ) ; } else { // This is a generalized version of the calculation in add ( double , double ) above . Note that
// non - finite inputs will have sumOfProductsOfDeltas = NaN , so non - finite values will result
// in NaN naturally .
sumOfProductsOfDeltas += values . sumOfProductsOfDeltas ( ) + ( values . xStats ( ) . mean ( ) - xStats . mean ( ) ) * ( values . yStats ( ) . mean ( ) - yStats . mean ( ) ) * values . count ( ) ; } yStats . addAll ( values . yStats ( ) ) ;


signature:
public class PairedStatsAccumulator { /** * Returns the < a href = " http : / / mathworld . wolfram . com / CorrelationCoefficient . html " > Pearson ' s or
 * product - moment correlation coefficient < / a > of the values . The count must greater than one , and
 * the { @ code x } and { @ code y } values must both have non - zero population variance ( i . e . { @ code
 * xStats ( ) . populationVariance ( ) > 0.0 & & yStats ( ) . populationVariance ( ) > 0.0 } ) . The result is not
 * guaranteed to be exactly + / - 1 even when the data are perfectly ( anti - ) correlated , due to
 * numerical errors . However , it is guaranteed to be in the inclusive range [ - 1 , + 1 ] .
 * < h3 > Non - finite values < / h3 >
 * < p > If the dataset contains any non - finite values ( { @ link Double # POSITIVE _ INFINITY } , { @ link
 * Double # NEGATIVE _ INFINITY } , or { @ link Double # NaN } ) then the result is { @ link Double # NaN } .
 * @ throws IllegalStateException if the dataset is empty or contains a single pair of values , or
 * either the { @ code x } and { @ code y } dataset has zero population variance */
public final double pearsonsCorrelationCoefficient ( ) { } }

implementation:
checkState ( count ( ) > 1 ) ; if ( isNaN ( sumOfProductsOfDeltas ) ) { return NaN ; } double xSumOfSquaresOfDeltas = xStats . sumOfSquaresOfDeltas ( ) ; double ySumOfSquaresOfDeltas = yStats . sumOfSquaresOfDeltas ( ) ; checkState ( xSumOfSquaresOfDeltas > 0.0 ) ; checkState ( ySumOfSquaresOfDeltas > 0.0 ) ; // The product of two positive numbers can be zero if the multiplication underflowed . We
// force a positive value by effectively rounding up to MIN _ VALUE .
double productOfSumsOfSquaresOfDeltas = ensurePositive ( xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas ) ; return ensureInUnitRange ( sumOfProductsOfDeltas / Math . sqrt ( productOfSumsOfSquaresOfDeltas ) ) ;


signature:
public class PairedStatsAccumulator { /** * Returns a linear transformation giving the best fit to the data according to < a
 * href = " http : / / mathworld . wolfram . com / LeastSquaresFitting . html " > Ordinary Least Squares linear
 * regression < / a > of { @ code y } as a function of { @ code x } . The count must be greater than one , and
 * either the { @ code x } or { @ code y } data must have a non - zero population variance ( i . e . { @ code
 * xStats ( ) . populationVariance ( ) > 0.0 | | yStats ( ) . populationVariance ( ) > 0.0 } ) . The result is
 * guaranteed to be horizontal if there is variance in the { @ code x } data but not the { @ code y }
 * data , and vertical if there is variance in the { @ code y } data but not the { @ code x } data .
 * < p > This fit minimizes the root - mean - square error in { @ code y } as a function of { @ code x } . This
 * error is defined as the square root of the mean of the squares of the differences between the
 * actual { @ code y } values of the data and the values predicted by the fit for the { @ code x }
 * values ( i . e . it is the square root of the mean of the squares of the vertical distances between
 * the data points and the best fit line ) . For this fit , this error is a fraction { @ code sqrt ( 1 -
 * R * R ) } of the population standard deviation of { @ code y } , where { @ code R } is the Pearson ' s
 * correlation coefficient ( as given by { @ link # pearsonsCorrelationCoefficient ( ) } ) .
 * < p > The corresponding root - mean - square error in { @ code x } as a function of { @ code y } is a
 * fraction { @ code sqrt ( 1 / ( R * R ) - 1 ) } of the population standard deviation of { @ code x } . This fit
 * does not normally minimize that error : to do that , you should swap the roles of { @ code x } and
 * { @ code y } .
 * < h3 > Non - finite values < / h3 >
 * < p > If the dataset contains any non - finite values ( { @ link Double # POSITIVE _ INFINITY } , { @ link
 * Double # NEGATIVE _ INFINITY } , or { @ link Double # NaN } ) then the result is { @ link
 * LinearTransformation # forNaN ( ) } .
 * @ throws IllegalStateException if the dataset is empty or contains a single pair of values , or
 * both the { @ code x } and { @ code y } dataset have zero population variance */
public final LinearTransformation leastSquaresFit ( ) { } }

implementation: checkState ( count ( ) > 1 ) ; if ( isNaN ( sumOfProductsOfDeltas ) ) { return LinearTransformation . forNaN ( ) ; } double xSumOfSquaresOfDeltas = xStats . sumOfSquaresOfDeltas ( ) ; if ( xSumOfSquaresOfDeltas > 0.0 ) { if ( yStats . sumOfSquaresOfDeltas ( ) > 0.0 ) { return LinearTransformation . mapping ( xStats . mean ( ) , yStats . mean ( ) ) . withSlope ( sumOfProductsOfDeltas / xSumOfSquaresOfDeltas ) ; } else { return LinearTransformation . horizontal ( yStats . mean ( ) ) ; } } else { checkState ( yStats . sumOfSquaresOfDeltas ( ) > 0.0 ) ; return LinearTransformation . vertical ( xStats . mean ( ) ) ; }


signature:
public class ImmutableClassToInstanceMap { /** * Returns an { @ code ImmutableClassToInstanceMap } containing a single entry .
 * @ since 19.0 */
public static < B , T extends B > ImmutableClassToInstanceMap < B > of ( Class < T > type , T value ) { } }

implementation: ImmutableMap < Class < ? extends B > , B > map = ImmutableMap . < Class < ? extends B > , B > of ( type , value ) ; return new ImmutableClassToInstanceMap < B > ( map ) ;


signature:
public class ImmutableClassToInstanceMap { /** * Returns an immutable map containing the same entries as { @ code map } . If { @ code map } somehow
 * contains entries with duplicate keys ( for example , if it is a { @ code SortedMap } whose
 * comparator is not < i > consistent with equals < / i > ) , the results of this method are undefined .
 * < p > < b > Note : < / b > Despite what the method name suggests , if { @ code map } is an { @ code
 * ImmutableClassToInstanceMap } , no copy will actually be performed .
 * @ throws NullPointerException if any key or value in { @ code map } is null
 * @ throws ClassCastException if any value is not an instance of the type specified by its key */
public static < B , S extends B > ImmutableClassToInstanceMap < B > copyOf ( Map < ? extends Class < ? extends S > , ? extends S > map ) { } }

implementation:
if ( map instanceof ImmutableClassToInstanceMap ) { @ SuppressWarnings ( "unchecked" ) // covariant casts safe ( unmodifiable )
// Eclipse won ' t compile if we cast to the parameterized type .
ImmutableClassToInstanceMap < B > cast = ( ImmutableClassToInstanceMap ) map ; return cast ; } return new Builder < B > ( ) . putAll ( map ) . build ( ) ;


signature:
public class Platform { /** * Equivalent to Arrays . copyOfRange ( source , from , to , arrayOfType . getClass ( ) ) . */
static < T > T [ ] copy ( Object [ ] source , int from , int to , T [ ] arrayOfType ) { } }

implementation: T [ ] result = newArray ( arrayOfType , to - from ) ; System . arraycopy ( source , from , result , 0 , to - from ) ; return result ;


signature:
public class BloomFilter { /** * Returns a { @ code Collector } expecting the specified number of insertions , and yielding a { @ link
 * BloomFilter } with false positive probability 3 % .
 * < p > Note that if the { @ code Collector } receives significantly more elements than specified , the
 * resulting { @ code BloomFilter } will suffer a sharp deterioration of its false positive
 * probability .
 * < p > The constructed { @ code BloomFilter } will be serializable if the provided { @ code Funnel < T > }
 * is .
 * < p > It is recommended that the funnel be implemented as a Java enum . This has the benefit of
 * ensuring proper serialization and deserialization , which is important since { @ link # equals }
 * also relies on object identity of funnels .
 * @ param funnel the funnel of T ' s that the constructed { @ code BloomFilter } will use
 * @ param expectedInsertions the number of expected insertions to the constructed { @ code
 * BloomFilter } ; must be positive
 * @ return a { @ code Collector } generating a { @ code BloomFilter } of the received elements
 * @ since 23.0 */
public static < T > Collector < T , ? , BloomFilter < T > > toBloomFilter ( Funnel < ? super T > funnel , long expectedInsertions ) { } }

implementation: return toBloomFilter ( funnel , expectedInsertions , 0.03 ) ;


signature:
public class BloomFilter { /** * Returns a { @ code Collector } expecting the specified number of insertions , and yielding a { @ link
 * BloomFilter } with the specified expected false positive probability .
 * < p > Note that if the { @ code Collector } receives significantly more elements than specified , the
 * resulting { @ code BloomFilter } will suffer a sharp deterioration of its false positive
 * probability .
 * < p > The constructed { @ code BloomFilter } will be serializable if the provided { @ code Funnel < T > }
 * is .
 * < p > It is recommended that the funnel be implemented as a Java enum . This has the benefit of
 * ensuring proper serialization and deserialization , which is important since { @ link # equals }
 * also relies on object identity of funnels .
 * @ param funnel the funnel of T ' s that the constructed { @ code BloomFilter } will use
 * @ param expectedInsertions the number of expected insertions to the constructed { @ code
 * BloomFilter } ; must be positive
 * @ param fpp the desired false positive probability ( must be positive and less than 1.0)
 * @ return a { @ code Collector } generating a { @ code BloomFilter } of the received elements
 * @ since 23.0 */
public static < T > Collector < T , ? , BloomFilter < T > > toBloomFilter ( Funnel < ? super T > funnel , long expectedInsertions , double fpp ) { } }

implementation: checkNotNull ( funnel ) ; checkArgument ( expectedInsertions >= 0 , "Expected insertions (%s) must be >= 0" , expectedInsertions ) ; checkArgument ( fpp > 0.0 , "False positive probability (%s) must be > 0.0" , fpp ) ; checkArgument ( fpp < 1.0 , "False positive probability (%s) must be < 1.0" , fpp ) ; return Collector . of ( ( ) -> BloomFilter . create ( funnel , expectedInsertions , fpp ) , BloomFilter :: put , ( bf1 , bf2 ) -> { bf1 . putAll ( bf2 ) ; return bf1 ; } , Collector . Characteristics . UNORDERED , Collector . Characteristics . CONCURRENT ) ;


signature:
public class RemovalNotification { /** * Creates a new { @ code RemovalNotification } for the given { @ code key } / { @ code value } pair , with
 * the given { @ code cause } for the removal . The { @ code key } and / or { @ code value } may be { @ code
 * null } if they were already garbage collected .
 * @ since 19.0 */
public static < K , V > RemovalNotification < K , V > create ( @ Nullable K key , @ Nullable V value , RemovalCause cause ) { } }

implementation: return new RemovalNotification ( key , value , cause ) ;


signature:
public class ConcurrentHashMultiset { /** * TODO ( cpovirk ) : remove and removeExactly currently accept null inputs only
 * if occurrences = = 0 . This satisfies both NullPointerTester and
 * CollectionRemoveTester . testRemove _ nullAllowed , but it ' s not clear that it ' s
 * a good policy , especially because , in order for the test to pass , the
 * parameter must be misleadingly annotated as @ Nullable . I suspect that
 * we ' ll want to remove @ Nullable , add an eager checkNotNull , and loosen up
 * testRemove _ nullAllowed . */
@ CanIgnoreReturnValue @ Override public int remove ( @ Nullable Object element , int occurrences ) { } }

implementation:
if ( occurrences == 0 ) { return count ( element ) ; } CollectPreconditions . checkPositive ( occurrences , "occurences" ) ; AtomicInteger existingCounter = Maps . safeGet ( countMap , element ) ; if ( existingCounter == null ) { return 0 ; } while ( true ) { int oldValue = existingCounter . get ( ) ; if ( oldValue != 0 ) { int newValue = Math . max ( 0 , oldValue - occurrences ) ; if ( existingCounter . compareAndSet ( oldValue , newValue ) ) { if ( newValue == 0 ) { // Just CASed to 0 ; remove the entry to clean up the map . If the removal fails ,
// another thread has already replaced it with a new counter , which is fine .
countMap . remove ( element , existingCounter ) ; } return oldValue ; } } else { return 0 ; } }


signature:
public class ConcurrentHashMultiset { /** * Removes exactly the specified number of occurrences of { @ code element } , or makes no change if
 * this is not possible .
 * < p > This method , in contrast to { @ link # remove ( Object , int ) } , has no effect when the element
 * count is smaller than { @ code occurrences } .
 * @ param element the element to remove
 * @ param occurrences the number of occurrences of { @ code element } to remove
 * @ return { @ code true } if the removal was possible ( including if { @ code occurrences } is zero )
 * @ throws IllegalArgumentException if { @ code occurrences } is negative */
@ CanIgnoreReturnValue public boolean removeExactly ( @ Nullable Object element , int occurrences ) { } }

implementation:
if ( occurrences == 0 ) { return true ; } CollectPreconditions . checkPositive ( occurrences , "occurences" ) ; AtomicInteger existingCounter = Maps . safeGet ( countMap , element ) ; if ( existingCounter == null ) { return false ; } while ( true ) { int oldValue = existingCounter . get ( ) ; if ( oldValue < occurrences ) { return false ; } int newValue = oldValue - occurrences ; if ( existingCounter . compareAndSet ( oldValue , newValue ) ) { if ( newValue == 0 ) { // Just CASed to 0 ; remove the entry to clean up the map . If the removal fails ,
// another thread has already replaced it with a new counter , which is fine .
countMap . remove ( element , existingCounter ) ; } return true ; } }


signature:
public class Bytes { /** * Returns an array containing each value of { @ code collection } , converted to a { @ code byte } value
 * in the manner of { @ link Number # byteValue } .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * @ param collection a collection of { @ code Number } instances
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null
 * @ since 1.0 ( parameter was { @ code Collection < Byte > } before 12.0) */
public static byte [ ] toArray ( Collection < ? extends Number > collection ) { } }

implementation:
if ( collection instanceof ByteArrayAsList ) { return ( ( ByteArrayAsList ) collection ) . toByteArray ( ) ; } Object [ ] boxedArray = collection . toArray ( ) ; int len = boxedArray . length ; byte [ ] array = new byte [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { // checkNotNull for GWT ( do not optimize )
array [ i ] = ( ( Number ) checkNotNull ( boxedArray [ i ] ) ) . byteValue ( ) ; } return array ;