signature:
public class CacheBuilder { /** * Specifies the weigher to use in determining the weight of entries . Entry weight is taken into
 * consideration by { @ link # maximumWeight ( long ) } when determining which entries to evict , and use
 * of this method requires a corresponding call to { @ link # maximumWeight ( long ) } prior to calling
 * { @ link # build } . Weights are measured and recorded when entries are inserted into the cache , and
 * are thus effectively static during the lifetime of a cache entry .
 * < p > When the weight of an entry is zero it will not be considered for size - based eviction
 * ( though it still may be evicted by other means ) .
 * < p > < b > Important note : < / b > Instead of returning < em > this < / em > as a { @ code CacheBuilder }
 * instance , this method returns { @ code CacheBuilder < K1 , V1 > } . From this point on , either the
 * original reference or the returned reference may be used to complete configuration and build
 * the cache , but only the " generic " one is type - safe . That is , it will properly prevent you from
 * building caches whose key or value types are incompatible with the types accepted by the
 * weigher already provided ; the { @ code CacheBuilder } type cannot do this . For best results ,
 * simply use the standard method - chaining idiom , as illustrated in the documentation at top ,
 * configuring a { @ code CacheBuilder } and building your { @ link Cache } all in a single statement .
 * < p > < b > Warning : < / b > if you ignore the above advice , and use this { @ code CacheBuilder } to build a
 * cache whose key or value type is incompatible with the weigher , you will likely experience a
 * { @ link ClassCastException } at some < i > undefined < / i > point in the future .
 * @ param weigher the weigher to use in calculating the weight of cache entries
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalArgumentException if { @ code size } is negative
 * @ throws IllegalStateException if a maximum size was already set
 * @ since 11.0 */
@ GwtIncompatible // To be supported
public < K1 extends K , V1 extends V > CacheBuilder < K1 , V1 > weigher ( Weigher < ? super K1 , ? super V1 > weigher ) { } }

implementation:
checkState ( this . weigher == null ) ; if ( strictParsing ) { checkState ( this . maximumSize == UNSET_INT , "weigher can not be combined with maximum size" , this . maximumSize ) ; } // safely limiting the kinds of caches this can produce
@ SuppressWarnings ( "unchecked" ) CacheBuilder < K1 , V1 > me = ( CacheBuilder < K1 , V1 > ) this ; me . weigher = checkNotNull ( weigher ) ; return me ;


signature:
public class CacheBuilder { /** * Make a safe contravariant cast now so we don ' t have to do it over and over . */
@ SuppressWarnings ( "unchecked" ) < K1 extends K , V1 extends V > Weigher < K1 , V1 > getWeigher ( ) { } }

implementation: return ( Weigher < K1 , V1 > ) MoreObjects . firstNonNull ( weigher , OneWeigher . INSTANCE ) ;


signature:
public class CacheBuilder { /** * Specifies a nanosecond - precision time source for this cache . By default , { @ link
 * System # nanoTime } is used .
 * < p > The primary intent of this method is to facilitate testing of caches with a fake or mock
 * time source .
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalStateException if a ticker was already set */
public CacheBuilder < K , V > ticker ( Ticker ticker ) { } }

implementation: checkState ( this . ticker == null ) ; this . ticker = checkNotNull ( ticker ) ; return this ;


signature:
public class CacheBuilder { /** * Specifies a listener instance that caches should notify each time an entry is removed for any
 * { @ linkplain RemovalCause reason } . Each cache created by this builder will invoke this listener
 * as part of the routine maintenance described in the class documentation above .
 * < p > < b > Warning : < / b > after invoking this method , do not continue to use < i > this < / i > cache builder
 * reference ; instead use the reference this method < i > returns < / i > . At runtime , these point to the
 * same instance , but only the returned reference has the correct generic type information so as
 * to ensure type safety . For best results , use the standard method - chaining idiom illustrated in
 * the class documentation above , configuring a builder and building your cache in a single
 * statement . Failure to heed this advice can result in a { @ link ClassCastException } being thrown
 * by a cache operation at some < i > undefined < / i > point in the future .
 * < p > < b > Warning : < / b > any exception thrown by { @ code listener } will < i > not < / i > be propagated to
 * the { @ code Cache } user , only logged via a { @ link Logger } .
 * @ return the cache builder reference that should be used instead of { @ code this } for any
 * remaining configuration and cache building
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalStateException if a removal listener was already set */
@ CheckReturnValue public < K1 extends K , V1 extends V > CacheBuilder < K1 , V1 > removalListener ( RemovalListener < ? super K1 , ? super V1 > listener ) { } }

implementation:
checkState ( this . removalListener == null ) ; // safely limiting the kinds of caches this can produce
@ SuppressWarnings ( "unchecked" ) CacheBuilder < K1 , V1 > me = ( CacheBuilder < K1 , V1 > ) this ; me . removalListener = checkNotNull ( listener ) ; return me ;


signature:
public class CacheBuilder { /** * Make a safe contravariant cast now so we don ' t have to do it over and over . */
@ SuppressWarnings ( "unchecked" ) < K1 extends K , V1 extends V > RemovalListener < K1 , V1 > getRemovalListener ( ) { } }

implementation: return ( RemovalListener < K1 , V1 > ) MoreObjects . firstNonNull ( removalListener , NullListener . INSTANCE ) ;


signature:
public class CacheBuilder { /** * Builds a cache , which either returns an already - loaded value for a given key or atomically
 * computes or retrieves it using the supplied { @ code CacheLoader } . If another thread is currently
 * loading the value for this key , simply waits for that thread to finish and returns its loaded
 * value . Note that multiple threads can concurrently load values for distinct keys .
 * < p > This method does not alter the state of this { @ code CacheBuilder } instance , so it can be
 * invoked again to create multiple independent caches .
 * @ param loader the cache loader used to obtain new values
 * @ return a cache having the requested features */
public < K1 extends K , V1 extends V > LoadingCache < K1 , V1 > build ( CacheLoader < ? super K1 , V1 > loader ) { } }

implementation: checkWeightWithWeigher ( ) ; return new LocalCache . LocalLoadingCache < > ( this , loader ) ;


signature:
public class CacheBuilder { /** * Builds a cache which does not automatically load values when keys are requested .
 * < p > Consider { @ link # build ( CacheLoader ) } instead , if it is feasible to implement a { @ code
 * CacheLoader } .
 * < p > This method does not alter the state of this { @ code CacheBuilder } instance , so it can be
 * invoked again to create multiple independent caches .
 * @ return a cache having the requested features
 * @ since 11.0 */
public < K1 extends K , V1 extends V > Cache < K1 , V1 > build ( ) { } }

implementation: checkWeightWithWeigher ( ) ; checkNonLoadingCache ( ) ; return new LocalCache . LocalManualCache < > ( this ) ;


signature:
public class PairedStats { /** * Gets a byte array representation of this instance .
 * < p > < b > Note : < / b > No guarantees are made regarding stability of the representation between
 * versions . */
public byte [ ] toByteArray ( ) { } }

implementation: ByteBuffer buffer = ByteBuffer . allocate ( BYTES ) . order ( ByteOrder . LITTLE_ENDIAN ) ; xStats . writeTo ( buffer ) ; yStats . writeTo ( buffer ) ; buffer . putDouble ( sumOfProductsOfDeltas ) ; return buffer . array ( ) ;


signature:
public class PairedStats { /** * Creates a { @ link PairedStats } instance from the given byte representation which was obtained by
 * { @ link # toByteArray } .
 * < p > < b > Note : < / b > No guarantees are made regarding stability of the representation between
 * versions . */
public static PairedStats fromByteArray ( byte [ ] byteArray ) { } }

implementation: checkNotNull ( byteArray ) ; checkArgument ( byteArray . length == BYTES , "Expected PairedStats.BYTES = %s, got %s" , BYTES , byteArray . length ) ; ByteBuffer buffer = ByteBuffer . wrap ( byteArray ) . order ( ByteOrder . LITTLE_ENDIAN ) ; Stats xStats = Stats . readFrom ( buffer ) ; Stats yStats = Stats . readFrom ( buffer ) ; double sumOfProductsOfDeltas = buffer . getDouble ( ) ; return new PairedStats ( xStats , yStats , sumOfProductsOfDeltas ) ;


signature:
public class TopKSelector { /** * Returns a { @ code TopKSelector } that collects the lowest { @ code k } elements added to it ,
 * relative to the natural ordering of the elements , and returns them via { @ link # topK } in
 * ascending order .
 * @ throws IllegalArgumentException if { @ code k < 0} */
public static < T extends Comparable < ? super T > > TopKSelector < T > least ( int k ) { } }

implementation: return least ( k , Ordering . natural ( ) ) ;


signature:
public class TopKSelector { /** * Returns a { @ code TopKSelector } that collects the lowest { @ code k } elements added to it ,
 * relative to the specified comparator , and returns them via { @ link # topK } in ascending order .
 * @ throws IllegalArgumentException if { @ code k < 0} */
public static < T > TopKSelector < T > least ( int k , Comparator < ? super T > comparator ) { } }

implementation: return new TopKSelector < T > ( comparator , k ) ;


signature:
public class TopKSelector { /** * Quickselects the top k elements from the 2k elements in the buffer . O ( k ) expected time , O ( k log
 * k ) worst case . */
private void trim ( ) { } }

implementation:
int left = 0 ; int right = 2 * k - 1 ; int minThresholdPosition = 0 ; // The leftmost position at which the greatest of the k lower elements
// - - the new value of threshold - - might be found .
int iterations = 0 ; int maxIterations = IntMath . log2 ( right - left , RoundingMode . CEILING ) * 3 ; while ( left < right ) { int pivotIndex = ( left + right + 1 ) >>> 1 ; int pivotNewIndex = partition ( left , right , pivotIndex ) ; if ( pivotNewIndex > k ) { right = pivotNewIndex - 1 ; } else if ( pivotNewIndex < k ) { left = Math . max ( pivotNewIndex , left + 1 ) ; minThresholdPosition = pivotNewIndex ; } else { break ; } iterations ++ ; if ( iterations >= maxIterations ) { // We ' ve already taken O ( k log k ) , let ' s make sure we don ' t take longer than O ( k log k ) .
Arrays . sort ( buffer , left , right , comparator ) ; break ; } } bufferSize = k ; threshold = buffer [ minThresholdPosition ] ; for ( int i = minThresholdPosition + 1 ; i < k ; i ++ ) { if ( comparator . compare ( buffer [ i ] , threshold ) > 0 ) { threshold = buffer [ i ] ; } }


signature:
public class TopKSelector { /** * Partitions the contents of buffer in the range [ left , right ] around the pivot element
 * previously stored in buffer [ pivotValue ] . Returns the new index of the pivot element ,
 * pivotNewIndex , so that everything in [ left , pivotNewIndex ] is ≤ pivotValue and everything in
 * ( pivotNewIndex , right ] is greater than pivotValue . */
private int partition ( int left , int right , int pivotIndex ) { } }

implementation: T pivotValue = buffer [ pivotIndex ] ; buffer [ pivotIndex ] = buffer [ right ] ; int pivotNewIndex = left ; for ( int i = left ; i < right ; i ++ ) { if ( comparator . compare ( buffer [ i ] , pivotValue ) < 0 ) { swap ( pivotNewIndex , i ) ; pivotNewIndex ++ ; } } buffer [ right ] = buffer [ pivotNewIndex ] ; buffer [ pivotNewIndex ] = pivotValue ; return pivotNewIndex ;


signature:
public class TopKSelector { /** * Returns the top { @ code k } elements offered to this { @ code TopKSelector } , or all elements if
 * fewer than { @ code k } have been offered , in the order specified by the factory used to create
 * this { @ code TopKSelector } .
 * < p > The returned list is an unmodifiable copy and will not be affected by further changes to
 * this { @ code TopKSelector } . This method returns in O ( k log k ) time . */
public List < T > topK ( ) { } }

implementation:
Arrays . sort ( buffer , 0 , bufferSize , comparator ) ; if ( bufferSize > k ) { Arrays . fill ( buffer , k , buffer . length , null ) ; bufferSize = k ; threshold = buffer [ k - 1 ] ; } // we have to support null elements , so no ImmutableList for us
return Collections . unmodifiableList ( Arrays . asList ( Arrays . copyOf ( buffer , bufferSize ) ) ) ;


signature:
public class BigIntegerMath { /** * Returns { @ code true } if { @ code x } represents a power of two . */
public static boolean isPowerOfTwo ( BigInteger x ) { } }

implementation: checkNotNull ( x ) ; return x . signum ( ) > 0 && x . getLowestSetBit ( ) == x . bitLength ( ) - 1 ;


signature:
public class BigIntegerMath { /** * Returns the base - 10 logarithm of { @ code x } , rounded according to the specified rounding mode .
 * @ throws IllegalArgumentException if { @ code x < = 0}
 * @ throws ArithmeticException if { @ code mode } is { @ link RoundingMode # UNNECESSARY } and { @ code x }
 * is not a power of ten */
@ GwtIncompatible // TODO
@ SuppressWarnings ( "fallthrough" ) public static int log10 ( BigInteger x , RoundingMode mode ) { } }

implementation:
checkPositive ( "x" , x ) ; if ( fitsInLong ( x ) ) { return LongMath . log10 ( x . longValue ( ) , mode ) ; } int approxLog10 = ( int ) ( log2 ( x , FLOOR ) * LN_2 / LN_10 ) ; BigInteger approxPow = BigInteger . TEN . pow ( approxLog10 ) ; int approxCmp = approxPow . compareTo ( x ) ; /* * We adjust approxLog10 and approxPow until they ' re equal to floor ( log10 ( x ) ) and
 * 10 ^ floor ( log10 ( x ) ) . */
if ( approxCmp > 0 ) { /* * The code is written so that even completely incorrect approximations will still yield the
 * correct answer eventually , but in practice this branch should almost never be entered , and
 * even then the loop should not run more than once . */
do { approxLog10 -- ; approxPow = approxPow . divide ( BigInteger . TEN ) ; approxCmp = approxPow . compareTo ( x ) ; } while ( approxCmp > 0 ) ; } else { BigInteger nextPow = BigInteger . TEN . multiply ( approxPow ) ; int nextCmp = nextPow . compareTo ( x ) ; while ( nextCmp <= 0 ) { approxLog10 ++ ; approxPow = nextPow ; approxCmp = nextCmp ; nextPow = BigInteger . TEN . multiply ( approxPow ) ; nextCmp = nextPow . compareTo ( x ) ; } } int floorLog = approxLog10 ; BigInteger floorPow = approxPow ; int floorCmp = approxCmp ; switch ( mode ) { case UNNECESSARY : checkRoundingUnnecessary ( floorCmp == 0 ) ; // fall through
case FLOOR : case DOWN : return floorLog ; case CEILING : case UP : return floorPow . equals ( x ) ? floorLog : floorLog + 1 ; case HALF_DOWN : case HALF_UP : case HALF_EVEN : // Since sqrt ( 10 ) is irrational , log10 ( x ) - floorLog can never be exactly 0.5
BigInteger x2 = x . pow ( 2 ) ; BigInteger halfPowerSquared = floorPow . pow ( 2 ) . multiply ( BigInteger . TEN ) ; return ( x2 . compareTo ( halfPowerSquared ) <= 0 ) ? floorLog : floorLog + 1 ; default : throw new AssertionError ( ) ; }


signature:
public class BigIntegerMath { /** * Returns { @ code n } choose { @ code k } , also known as the binomial coefficient of { @ code n } and
 * { @ code k } , that is , { @ code n ! / ( k ! ( n - k ) ! ) } .
 * < p > < b > Warning : < / b > the result can take as much as < i > O ( k log n ) < / i > space .
 * @ throws IllegalArgumentException if { @ code n < 0 } , { @ code k < 0 } , or { @ code k > n } */
public static BigInteger binomial ( int n , int k ) { } }

implementation:
checkNonNegative ( "n" , n ) ; checkNonNegative ( "k" , k ) ; checkArgument ( k <= n , "k (%s) > n (%s)" , k , n ) ; if ( k > ( n >> 1 ) ) { k = n - k ; } if ( k < LongMath . biggestBinomials . length && n <= LongMath . biggestBinomials [ k ] ) { return BigInteger . valueOf ( LongMath . binomial ( n , k ) ) ; } BigInteger accum = BigInteger . ONE ; long numeratorAccum = n ; long denominatorAccum = 1 ; int bits = LongMath . log2 ( n , RoundingMode . CEILING ) ; int numeratorBits = bits ; for ( int i = 1 ; i < k ; i ++ ) { int p = n - i ; int q = i + 1 ; // log2 ( p ) > = bits - 1 , because p > = n / 2
if ( numeratorBits + bits >= Long . SIZE - 1 ) { // The numerator is as big as it can get without risking overflow .
// Multiply numeratorAccum / denominatorAccum into accum .
accum = accum . multiply ( BigInteger . valueOf ( numeratorAccum ) ) . divide ( BigInteger . valueOf ( denominatorAccum ) ) ; numeratorAccum = p ; denominatorAccum = q ; numeratorBits = bits ; } else { // We can definitely multiply into the long accumulators without overflowing them .
numeratorAccum *= p ; denominatorAccum *= q ; numeratorBits += bits ; } } return accum . multiply ( BigInteger . valueOf ( numeratorAccum ) ) . divide ( BigInteger . valueOf ( denominatorAccum ) ) ;


signature:
public class EndpointPairIterator { /** * Called after { @ link # successorIterator } is exhausted . Advances { @ link # node } to the next node
 * and updates { @ link # successorIterator } to iterate through the successors of { @ link # node } . */
protected final boolean advance ( ) { } }

implementation: checkState ( ! successorIterator . hasNext ( ) ) ; if ( ! nodeIterator . hasNext ( ) ) { return false ; } node = nodeIterator . next ( ) ; successorIterator = graph . successors ( node ) . iterator ( ) ; return true ;


signature:
public class ServiceManager { /** * Initiates service { @ linkplain Service # startAsync startup } on all the services being managed . It
 * is only valid to call this method if all of the services are { @ linkplain State # NEW new } .
 * @ return this
 * @ throws IllegalStateException if any of the Services are not { @ link State # NEW new } when the
 * method is called . */
@ CanIgnoreReturnValue public ServiceManager startAsync ( ) { } }

implementation:
for ( Service service : services ) { State state = service . state ( ) ; checkState ( state == NEW , "Service %s is %s, cannot start it." , service , state ) ; } for ( Service service : services ) { try { state . tryStartTiming ( service ) ; service . startAsync ( ) ; } catch ( IllegalStateException e ) { // This can happen if the service has already been started or stopped ( e . g . by another
// service or listener ) . Our contract says it is safe to call this method if
// all services were NEW when it was called , and this has already been verified above , so we
// don ' t propagate the exception .
logger . log ( Level . WARNING , "Unable to start Service " + service , e ) ; } } return this ;


signature:
public class ServiceManager { /** * Waits for the { @ link ServiceManager } to become { @ linkplain # isHealthy ( ) healthy } for no more
 * than the given time . The manager will become healthy after all the component services have
 * reached the { @ linkplain State # RUNNING running } state .
 * @ param timeout the maximum time to wait
 * @ param unit the time unit of the timeout argument
 * @ throws TimeoutException if not all of the services have finished starting within the deadline
 * @ throws IllegalStateException if the service manager reaches a state from which it cannot
 * become { @ linkplain # isHealthy ( ) healthy } . */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public void awaitHealthy ( long timeout , TimeUnit unit ) throws TimeoutException { } }

implementation: state . awaitHealthy ( timeout , unit ) ;


signature:
public class ServiceManager { /** * Waits for the all the services to reach a terminal state for no more than the given time . After
 * this method returns all services will either be { @ linkplain Service . State # TERMINATED
 * terminated } or { @ linkplain Service . State # FAILED failed } .
 * @ param timeout the maximum time to wait
 * @ param unit the time unit of the timeout argument
 * @ throws TimeoutException if not all of the services have stopped within the deadline */
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public void awaitStopped ( long timeout , TimeUnit unit ) throws TimeoutException { } }

implementation: state . awaitStopped ( timeout , unit ) ;


signature:
public class CompactHashMap { /** * Handle lazy allocation of arrays . */
void allocArrays ( ) { } }

implementation: Preconditions . checkState ( needsAllocArrays ( ) , "Arrays already allocated" ) ; int expectedSize = modCount ; int buckets = Hashing . closedTableSize ( expectedSize , LOAD_FACTOR ) ; this . table = newTable ( buckets ) ; this . entries = newEntries ( expectedSize ) ; this . keys = new Object [ expectedSize ] ; this . values = new Object [ expectedSize ] ;


signature:
public class CompactHashMap { /** * Resizes the internal entries array to the specified capacity , which may be greater or less than
 * the current capacity . */
void resizeEntries ( int newCapacity ) { } }

implementation: this . keys = Arrays . copyOf ( keys , newCapacity ) ; this . values = Arrays . copyOf ( values , newCapacity ) ; long [ ] entries = this . entries ; int oldCapacity = entries . length ; entries = Arrays . copyOf ( entries , newCapacity ) ; if ( newCapacity > oldCapacity ) { Arrays . fill ( entries , oldCapacity , newCapacity , UNSET ) ; } this . entries = entries ;


signature:
public class CompactHashMap { /** * The serial form currently mimics Android ' s java . util . HashMap version , e . g . see
 * http : / / omapzoom . org / ? p = platform / libcore . git ; a = blob ; f = luni / src / main / java / java / util / HashMap . java */
private void writeObject ( ObjectOutputStream stream ) throws IOException { } }

implementation: stream . defaultWriteObject ( ) ; stream . writeInt ( size ) ; for ( int i = firstEntryIndex ( ) ; i >= 0 ; i = getSuccessor ( i ) ) { stream . writeObject ( keys [ i ] ) ; stream . writeObject ( values [ i ] ) ; }


signature:
public class ListenableFutureTask { /** * Creates a { @ code ListenableFutureTask } that will upon running , execute the given { @ code
 * Callable } .
 * @ param callable the callable task
 * @ since 10.0 */
public static < V > ListenableFutureTask < V > create ( Callable < V > callable ) { } }

implementation: return new ListenableFutureTask < V > ( callable ) ;


signature:
public class ListenableFutureTask { /** * Creates a { @ code ListenableFutureTask } that will upon running , execute the given { @ code
 * Runnable } , and arrange that { @ code get } will return the given result on successful completion .
 * @ param runnable the runnable task
 * @ param result the result to return on successful completion . If you don ' t need a particular
 * result , consider using constructions of the form : { @ code ListenableFuture < ? > f =
 * ListenableFutureTask . create ( runnable , null ) }
 * @ since 10.0 */
public static < V > ListenableFutureTask < V > create ( Runnable runnable , @ NullableDecl V result ) { } }

implementation: return new ListenableFutureTask < V > ( runnable , result ) ;


signature:
public class StatsAccumulator { /** * Adds the given value to the dataset . */
public void add ( double value ) { } }

implementation:
if ( count == 0 ) { count = 1 ; mean = value ; min = value ; max = value ; if ( ! isFinite ( value ) ) { sumOfSquaresOfDeltas = NaN ; } } else { count ++ ; if ( isFinite ( value ) && isFinite ( mean ) ) { // Art of Computer Programming vol . 2 , Knuth , 4.2.2 , ( 15 ) and ( 16)
double delta = value - mean ; mean += delta / count ; sumOfSquaresOfDeltas += delta * ( value - mean ) ; } else { mean = calculateNewMeanNonFinite ( mean , value ) ; sumOfSquaresOfDeltas = NaN ; } min = Math . min ( min , value ) ; max = Math . max ( max , value ) ; }


signature:
public class StatsAccumulator { /** * Adds the given values to the dataset .
 * @ param values a series of values , which will be converted to { @ code double } values ( this may
 * cause loss of precision ) */
public void addAll ( Iterable < ? extends Number > values ) { } }

implementation: for ( Number value : values ) { add ( value . doubleValue ( ) ) ; }


signature:
public class StatsAccumulator { /** * Adds the given values to the dataset .
 * @ param values a series of values , which will be converted to { @ code double } values ( this may
 * cause loss of precision ) */
public void addAll ( Iterator < ? extends Number > values ) { } }

implementation: while ( values . hasNext ( ) ) { add ( values . next ( ) . doubleValue ( ) ) ; }


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

implementation:
if ( values . count ( ) == 0 ) { return ; } if ( count == 0 ) { count = values . count ( ) ; mean = values . mean ( ) ; sumOfSquaresOfDeltas = values . sumOfSquaresOfDeltas ( ) ; min = values . min ( ) ; max = values . max ( ) ; } else { count += values . count ( ) ; if ( isFinite ( mean ) && isFinite ( values . mean ( ) ) ) { // This is a generalized version of the calculation in add ( double ) above .
double delta = values . mean ( ) - mean ; mean += delta * values . count ( ) / count ; sumOfSquaresOfDeltas += values . sumOfSquaresOfDeltas ( ) + delta * ( values . mean ( ) - mean ) * values . count ( ) ; } else { mean = calculateNewMeanNonFinite ( mean , values . mean ( ) ) ; sumOfSquaresOfDeltas = NaN ; } min = Math . min ( min , values . min ( ) ) ; max = Math . max ( max , values . max ( ) ) ; }


signature:
public class StatsAccumulator { /** * Calculates the new value for the accumulated mean when a value is added , in the case where at
 * least one of the previous mean and the value is non - finite . */
static double calculateNewMeanNonFinite ( double previousMean , double value ) { } }

implementation:
/* * Desired behaviour is to match the results of applying the naive mean formula . In particular ,
 * the update formula can subtract infinities in cases where the naive formula would add them .
 * Consequently :
 * 1 . If the previous mean is finite and the new value is non - finite then the new mean is that
 * value ( whether it is NaN or infinity ) .
 * 2 . If the new value is finite and the previous mean is non - finite then the mean is unchanged
 * ( whether it is NaN or infinity ) .
 * 3 . If both the previous mean and the new value are non - finite and . . .
 * 3a . . . . either or both is NaN ( so mean ! = value ) then the new mean is NaN .
 * 3b . . . . they are both the same infinities ( so mean = = value ) then the mean is unchanged .
 * 3c . . . . they are different infinities ( so mean ! = value ) then the new mean is NaN . */
if ( isFinite ( previousMean ) ) { // This is case 1.
return value ; } else if ( isFinite ( value ) || previousMean == value ) { // This is case 2 . or 3b .
return previousMean ; } else { // This is case 3a . or 3c .
return NaN ; }


signature:
public class UnsignedInteger { /** * Returns an { @ code UnsignedInteger } that is equal to { @ code value } , if possible . The inverse
 * operation of { @ link # longValue ( ) } . */
public static UnsignedInteger valueOf ( long value ) { } }

implementation: checkArgument ( ( value & INT_MASK ) == value , "value (%s) is outside the range for an unsigned integer value" , value ) ; return fromIntBits ( ( int ) value ) ;


signature:
public class UnsignedInteger { /** * Returns a { @ code UnsignedInteger } representing the same value as the specified { @ link
 * BigInteger } . This is the inverse operation of { @ link # bigIntegerValue ( ) } .
 * @ throws IllegalArgumentException if { @ code value } is negative or { @ code value > = 2 ^ 32} */
public static UnsignedInteger valueOf ( BigInteger value ) { } }

implementation: checkNotNull ( value ) ; checkArgument ( value . signum ( ) >= 0 && value . bitLength ( ) <= Integer . SIZE , "value (%s) is outside the range for an unsigned integer value" , value ) ; return fromIntBits ( value . intValue ( ) ) ;


signature:
public class UnsignedInteger { /** * Returns an { @ code UnsignedInteger } holding the value of the specified { @ code String } , parsed as
 * an unsigned { @ code int } value in the specified radix .
 * @ throws NumberFormatException if the string does not contain a parsable unsigned { @ code int }
 * value */
public static UnsignedInteger valueOf ( String string , int radix ) { } }

implementation: return fromIntBits ( UnsignedInts . parseUnsignedInt ( string , radix ) ) ;


signature:
public class UnsignedInteger { /** * Returns this mod { @ code val } .
 * @ throws ArithmeticException if { @ code val } is zero
 * @ since 14.0 */
public UnsignedInteger mod ( UnsignedInteger val ) { } }

implementation: return fromIntBits ( UnsignedInts . remainder ( value , checkNotNull ( val ) . value ) ) ;


signature:
public class UnsignedInteger { /** * Compares this unsigned integer to another unsigned integer . Returns { @ code 0 } if they are
 * equal , a negative number if { @ code this < other } , and a positive number if { @ code this >
 * other } . */
@ Override public int compareTo ( UnsignedInteger other ) { } }

implementation: checkNotNull ( other ) ; return compare ( value , other . value ) ;


signature:
public class ForwardingMapEntry { /** * A sensible definition of { @ link # equals ( Object ) } in terms of { @ link # getKey ( ) } and { @ link
 * # getValue ( ) } . If you override either of these methods , you may wish to override { @ link
 * # equals ( Object ) } to forward to this implementation .
 * @ since 7.0 */
protected boolean standardEquals ( @ Nullable Object object ) { } }

implementation: if ( object instanceof Entry ) { Entry < ? , ? > that = ( Entry < ? , ? > ) object ; return Objects . equal ( this . getKey ( ) , that . getKey ( ) ) && Objects . equal ( this . getValue ( ) , that . getValue ( ) ) ; } return false ;


signature:
public class ForwardingMapEntry { /** * A sensible definition of { @ link # hashCode ( ) } in terms of { @ link # getKey ( ) } and { @ link
 * # getValue ( ) } . If you override either of these methods , you may wish to override { @ link
 * # hashCode ( ) } to forward to this implementation .
 * @ since 7.0 */
protected int standardHashCode ( ) { } }

implementation: K k = getKey ( ) ; V v = getValue ( ) ; return ( ( k == null ) ? 0 : k . hashCode ( ) ) ^ ( ( v == null ) ? 0 : v . hashCode ( ) ) ;


signature:
public class MutableClassToInstanceMap { /** * Returns a new { @ code MutableClassToInstanceMap } instance backed by a { @ link HashMap } using the
 * default initial capacity and load factor . */
public static < B > MutableClassToInstanceMap < B > create ( ) { } }

implementation: return new MutableClassToInstanceMap < B > ( new HashMap < Class < ? extends B > , B > ( ) ) ;


signature:
public class MutableClassToInstanceMap { /** * Returns a new { @ code MutableClassToInstanceMap } instance backed by a given empty { @ code
 * backingMap } . The caller surrenders control of the backing map , and thus should not allow any
 * direct references to it to remain accessible . */
public static < B > MutableClassToInstanceMap < B > create ( Map < Class < ? extends B > , B > backingMap ) { } }

implementation: return new MutableClassToInstanceMap < B > ( backingMap ) ;


signature:
public class ForwardingSortedSet { /** * unsafe , but worst case is a CCE is thrown , which callers will be expecting */
@ SuppressWarnings ( "unchecked" ) private int unsafeCompare ( @ NullableDecl Object o1 , @ NullableDecl Object o2 ) { } }

implementation: Comparator < ? super E > comparator = comparator ( ) ; return ( comparator == null ) ? ( ( Comparable < Object > ) o1 ) . compareTo ( o2 ) : ( ( Comparator < Object > ) comparator ) . compare ( o1 , o2 ) ;


signature:
public class ForwardingSortedSet { /** * A sensible definition of { @ link # contains } in terms of the { @ code first ( ) } method of { @ link
 * # tailSet } . If you override { @ link # tailSet } , you may wish to override { @ link # contains } to
 * forward to this implementation .
 * @ since 7.0 */
@ Override @ Beta protected boolean standardContains ( @ NullableDecl Object object ) { } }

implementation:
try { // any ClassCastExceptions are caught
@ SuppressWarnings ( "unchecked" ) SortedSet < Object > self = ( SortedSet < Object > ) this ; Object ceiling = self . tailSet ( object ) . first ( ) ; return unsafeCompare ( ceiling , object ) == 0 ; } catch ( ClassCastException | NoSuchElementException | NullPointerException e ) { return false ; }


signature:
public class ForwardingSortedSet { /** * A sensible default implementation of { @ link # subSet ( Object , Object ) } in terms of { @ link
 * # headSet ( Object ) } and { @ link # tailSet ( Object ) } . In some situations , you may wish to override
 * { @ link # subSet ( Object , Object ) } to forward to this implementation .
 * @ since 7.0 */
@ Beta protected SortedSet < E > standardSubSet ( E fromElement , E toElement ) { } }

implementation: return tailSet ( fromElement ) . headSet ( toElement ) ;


signature:
public class Ascii { /** * Returns a copy of the input character sequence in which all { @ linkplain # isUpperCase ( char )
 * uppercase ASCII characters } have been converted to lowercase . All other characters are copied
 * without modification .
 * @ since 14.0 */
public static String toLowerCase ( CharSequence chars ) { } }

implementation: if ( chars instanceof String ) { return toLowerCase ( ( String ) chars ) ; } char [ ] newChars = new char [ chars . length ( ) ] ; for ( int i = 0 ; i < newChars . length ; i ++ ) { newChars [ i ] = toLowerCase ( chars . charAt ( i ) ) ; } return String . valueOf ( newChars ) ;


signature:
public class Ascii { /** * Truncates the given character sequence to the given maximum length . If the length of the
 * sequence is greater than { @ code maxLength } , the returned string will be exactly { @ code
 * maxLength } chars in length and will end with the given { @ code truncationIndicator } . Otherwise ,
 * the sequence will be returned as a string with no changes to the content .
 * < p > Examples :
 * < pre > { @ code
 * Ascii . truncate ( " foobar " , 7 , " . . . " ) ; / / returns " foobar "
 * Ascii . truncate ( " foobar " , 5 , " . . . " ) ; / / returns " fo . . . "
 * } < / pre >
 * < p > < b > Note : < / b > This method < i > may < / i > work with certain non - ASCII text but is not safe for use
 * with arbitrary Unicode text . It is mostly intended for use with text that is known to be safe
 * for use with it ( such as all - ASCII text ) and for simple debugging text . When using this method ,
 * consider the following :
 * < ul >
 * < li > it may split surrogate pairs
 * < li > it may split characters and combining characters
 * < li > it does not consider word boundaries
 * < li > if truncating for display to users , there are other considerations that must be taken
 * into account
 * < li > the appropriate truncation indicator may be locale - dependent
 * < li > it is safe to use non - ASCII characters in the truncation indicator
 * < / ul >
 * @ throws IllegalArgumentException if { @ code maxLength } is less than the length of { @ code
 * truncationIndicator }
 * @ since 16.0 */
public static String truncate ( CharSequence seq , int maxLength , String truncationIndicator ) { } }

implementation:
checkNotNull ( seq ) ; // length to truncate the sequence to , not including the truncation indicator
int truncationLength = maxLength - truncationIndicator . length ( ) ; // in this worst case , this allows a maxLength equal to the length of the truncationIndicator ,
// meaning that a string will be truncated to just the truncation indicator itself
checkArgument ( truncationLength >= 0 , "maxLength (%s) must be >= length of the truncation indicator (%s)" , maxLength , truncationIndicator . length ( ) ) ; if ( seq . length ( ) <= maxLength ) { String string = seq . toString ( ) ; if ( string . length ( ) <= maxLength ) { return string ; } // if the length of the toString ( ) result was > maxLength for some reason , truncate that
seq = string ; } return new StringBuilder ( maxLength ) . append ( seq , 0 , truncationLength ) . append ( truncationIndicator ) . toString ( ) ;


signature:
public class Ascii { /** * Indicates whether the contents of the given character sequences { @ code s1 } and { @ code s2 } are
 * equal , ignoring the case of any ASCII alphabetic characters between { @ code ' a ' } and { @ code ' z ' }
 * or { @ code ' A ' } and { @ code ' Z ' } inclusive .
 * < p > This method is significantly faster than { @ link String # equalsIgnoreCase } and should be used
 * in preference if at least one of the parameters is known to contain only ASCII characters .
 * < p > Note however that this method does not always behave identically to expressions such as :
 * < ul >
 * < li > { @ code string . toUpperCase ( ) . equals ( " UPPER CASE ASCII " ) }
 * < li > { @ code string . toLowerCase ( ) . equals ( " lower case ascii " ) }
 * < / ul >
 * < p > due to case - folding of some non - ASCII characters ( which does not occur in { @ link
 * String # equalsIgnoreCase } ) . However in almost all cases that ASCII strings are used , the author
 * probably wanted the behavior provided by this method rather than the subtle and sometimes
 * surprising behavior of { @ code toUpperCase ( ) } and { @ code toLowerCase ( ) } .
 * @ since 16.0 */
public static boolean equalsIgnoreCase ( CharSequence s1 , CharSequence s2 ) { } }

implementation:
// Calling length ( ) is the null pointer check ( so do it before we can exit early ) .
int length = s1 . length ( ) ; if ( s1 == s2 ) { return true ; } if ( length != s2 . length ( ) ) { return false ; } for ( int i = 0 ; i < length ; i ++ ) { char c1 = s1 . charAt ( i ) ; char c2 = s2 . charAt ( i ) ; if ( c1 == c2 ) { continue ; } int alphaIndex = getAlphaIndex ( c1 ) ; // This was also benchmarked using ' & ' to avoid branching ( but always evaluate the rhs ) ,
// however this showed no obvious improvement .
if ( alphaIndex < 26 && alphaIndex == getAlphaIndex ( c2 ) ) { continue ; } return false ; } return true ;


signature:
public class ImmutableBiMapFauxverideShim { /** * Not supported . Use { @ link ImmutableBiMap # toImmutableBiMap } instead . This method exists only to
 * hide { @ link ImmutableMap # toImmutableMap ( Function , Function ) } from consumers of { @ code
 * ImmutableBiMap } .
 * @ throws UnsupportedOperationException always
 * @ deprecated Use { @ link ImmutableBiMap # toImmutableBiMap } . */
@ Deprecated public static < T , K , V > Collector < T , ? , ImmutableMap < K , V > > toImmutableMap ( Function < ? super T , ? extends K > keyFunction , Function < ? super T , ? extends V > valueFunction ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class Cut { /** * note : overridden by { BELOW , ABOVE } _ ALL */
@ Override public int compareTo ( Cut < C > that ) { } }

implementation:
if ( that == belowAll ( ) ) { return 1 ; } if ( that == aboveAll ( ) ) { return - 1 ; } int result = Range . compareOrThrow ( endpoint , that . endpoint ) ; if ( result != 0 ) { return result ; } // same value . below comes before above
return Booleans . compare ( this instanceof AboveValue , that instanceof AboveValue ) ;


signature:
public class Cut { /** * The implementation neither produces nor consumes any non - null instance of type C , so
 * casting the type parameter is safe . */
@ SuppressWarnings ( "unchecked" ) static < C extends Comparable > Cut < C > belowAll ( ) { } }

implementation: return ( Cut < C > ) BelowAll . INSTANCE ;


signature:
public class Cut { /** * The implementation neither produces nor consumes any non - null instance of
 * type C , so casting the type parameter is safe . */
@ SuppressWarnings ( "unchecked" ) static < C extends Comparable > Cut < C > aboveAll ( ) { } }

implementation: return ( Cut < C > ) AboveAll . INSTANCE ;


signature:
public class MoreObjects { /** * Returns the first of two given parameters that is not { @ code null } , if either is , or otherwise
 * throws a { @ link NullPointerException } .
 * < p > To find the first non - null element in an iterable , use { @ code Iterables . find ( iterable ,
 * Predicates . notNull ( ) ) } . For varargs , use { @ code Iterables . find ( Arrays . asList ( a , b , c , . . . ) ,
 * Predicates . notNull ( ) ) } , static importing as necessary .
 * < p > < b > Note : < / b > if { @ code first } is represented as an { @ link Optional } , this can be
 * accomplished with { @ link Optional # or ( Object ) first . or ( second ) } . That approach also allows for
 * lazy evaluation of the fallback instance , using { @ link Optional # or ( Supplier )
 * first . or ( supplier ) } .
 * @ return { @ code first } if it is non - null ; otherwise { @ code second } if it is non - null
 * @ throws NullPointerException if both { @ code first } and { @ code second } are null
 * @ since 18.0 ( since 3.0 as { @ code Objects . firstNonNull ( ) } ) . */
public static < T > T firstNonNull ( @ NullableDecl T first , @ NullableDecl T second ) { } }

implementation: if ( first != null ) { return first ; } if ( second != null ) { return second ; } throw new NullPointerException ( "Both parameters are null" ) ;


signature:
public class LineReader { /** * Reads a line of text . A line is considered to be terminated by any one of a line feed ( { @ code
 * ' \ n ' } ) , a carriage return ( { @ code ' \ r ' } ) , or a carriage return followed immediately by a
 * linefeed ( { @ code " \ r \ n " } ) .
 * @ return a { @ code String } containing the contents of the line , not including any
 * line - termination characters , or { @ code null } if the end of the stream has been reached .
 * @ throws IOException if an I / O error occurs */
@ CanIgnoreReturnValue // to skip a line
public String readLine ( ) throws IOException { } }

implementation:
while ( lines . peek ( ) == null ) { cbuf . clear ( ) ; // The default implementation of Reader # read ( CharBuffer ) allocates a
// temporary char [ ] , so we call Reader # read ( char [ ] , int , int ) instead .
int read = ( reader != null ) ? reader . read ( buf , 0 , buf . length ) : readable . read ( cbuf ) ; if ( read == - 1 ) { lineBuf . finish ( ) ; break ; } lineBuf . add ( buf , 0 , read ) ; } return lines . poll ( ) ;


signature:
public class DiscreteDomain { /** * Returns , conceptually , " origin + distance " , or equivalently , the result of calling { @ link
 * # next } on { @ code origin } { @ code distance } times . */
C offset ( C origin , long distance ) { } }

implementation: checkNonnegative ( distance , "distance" ) ; for ( long i = 0 ; i < distance ; i ++ ) { origin = next ( origin ) ; } return origin ;


signature:
public class ImmutableSet { /** * Returns an immutable set containing the given elements , minus duplicates , in the order each was
 * first specified . That is , if multiple elements are { @ linkplain Object # equals equal } , all except
 * the first are ignored . */
public static < E > ImmutableSet < E > of ( E e1 , E e2 , E e3 , E e4 ) { } }

implementation: return construct ( 4 , 4 , e1 , e2 , e3 , e4 ) ;


signature:
public class ImmutableSet { /** * Constructs an { @ code ImmutableSet } from the first { @ code n } elements of the specified array ,
 * which we have no particular reason to believe does or does not contain duplicates . If { @ code k }
 * is the size of the returned { @ code ImmutableSet } , then the unique elements of { @ code elements }
 * will be in the first { @ code k } positions , and { @ code elements [ i ] = = null } for { @ code k < = i <
 * < p > This may modify { @ code elements } . Additionally , if { @ code n = = elements . length } and { @ code
 * elements } contains no duplicates , { @ code elements } may be used without copying in the returned
 * { @ code ImmutableSet } , in which case the caller must not modify it .
 * < p > { @ code elements } may contain only values of type { @ code E } .
 * @ throws NullPointerException if any of the first { @ code n } elements of { @ code elements } is null */
private static < E > ImmutableSet < E > constructUnknownDuplication ( int n , Object ... elements ) { } }

implementation:
// Guess the size is " halfway between " all duplicates and no duplicates , on a log scale .
return construct ( n , Math . max ( ImmutableCollection . Builder . DEFAULT_INITIAL_CAPACITY , IntMath . sqrt ( n , RoundingMode . CEILING ) ) , elements ) ;


signature:
public class ImmutableSet { /** * Constructs an { @ code ImmutableSet } from the first { @ code n } elements of the specified array . If
 * { @ code k } is the size of the returned { @ code ImmutableSet } , then the unique elements of { @ code
 * elements } will be in the first { @ code k } positions , and { @ code elements [ i ] = = null } for { @ code
 * k < = i < n } .
 * < p > This may modify { @ code elements } . Additionally , if { @ code n = = elements . length } and { @ code
 * elements } contains no duplicates , { @ code elements } may be used without copying in the returned
 * { @ code ImmutableSet } , in which case it may no longer be modified .
 * < p > { @ code elements } may contain only values of type { @ code E } .
 * @ throws NullPointerException if any of the first { @ code n } elements of { @ code elements } is null */
private static < E > ImmutableSet < E > construct ( int n , int expectedSize , Object ... elements ) { } }

implementation:
switch ( n ) { case 0 : return of ( ) ; case 1 : @ SuppressWarnings ( "unchecked" ) // safe ; elements contains only E ' s
E elem = ( E ) elements [ 0 ] ; return of ( elem ) ; default : SetBuilderImpl < E > builder = new RegularSetBuilderImpl < E > ( expectedSize ) ; for ( int i = 0 ; i < n ; i ++ ) { @ SuppressWarnings ( "unchecked" ) E e = ( E ) checkNotNull ( elements [ i ] ) ; builder = builder . add ( e ) ; } return builder . review ( ) . build ( ) ; }


signature:
public class ImmutableSet { /** * Returns an immutable set containing each of { @ code elements } , minus duplicates , in the order
 * each appears first in the source collection .
 * < p > < b > Performance note : < / b > This method will sometimes recognize that the actual copy operation
 * is unnecessary ; for example , { @ code copyOf ( copyOf ( anArrayList ) ) } will copy the data only once .
 * This reduces the expense of habitually making defensive copies at API boundaries . However , the
 * precise conditions for skipping the copy operation are undefined .
 * @ throws NullPointerException if any of { @ code elements } is null
 * @ since 7.0 ( source - compatible since 2.0) */
public static < E > ImmutableSet < E > copyOf ( Collection < ? extends E > elements ) { } }

implementation:
/* * TODO ( lowasser ) : consider checking for ImmutableAsList here
 * TODO ( lowasser ) : consider checking for Multiset here */
// Don ' t refer to ImmutableSortedSet by name so it won ' t pull in all that code
if ( elements instanceof ImmutableSet && ! ( elements instanceof SortedSet ) ) { @ SuppressWarnings ( "unchecked" ) // all supported methods are covariant
ImmutableSet < E > set = ( ImmutableSet < E > ) elements ; if ( ! set . isPartialView ( ) ) { return set ; } } else if ( elements instanceof EnumSet ) { return copyOfEnumSet ( ( EnumSet ) elements ) ; } Object [ ] array = elements . toArray ( ) ; if ( elements instanceof Set ) { // assume probably no duplicates ( though it might be using different equality semantics )
return construct ( array . length , array . length , array ) ; } else { return constructUnknownDuplication ( array . length , array ) ; }


signature:
public class ImmutableSet { /** * Returns an immutable set containing each of { @ code elements } , minus duplicates , in the order
 * each appears first in the source iterable . This method iterates over { @ code elements } only
 * once .
 * < p > < b > Performance note : < / b > This method will sometimes recognize that the actual copy operation
 * is unnecessary ; for example , { @ code copyOf ( copyOf ( anArrayList ) ) } should copy the data only
 * once . This reduces the expense of habitually making defensive copies at API boundaries .
 * However , the precise conditions for skipping the copy operation are undefined .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableSet < E > copyOf ( Iterable < ? extends E > elements ) { } }

implementation: return ( elements instanceof Collection ) ? copyOf ( ( Collection < ? extends E > ) elements ) : copyOf ( elements . iterator ( ) ) ;


signature:
public class ImmutableSet { /** * Returns an immutable set containing each of { @ code elements } , minus duplicates , in the order
 * each appears first in the source array .
 * @ throws NullPointerException if any of { @ code elements } is null
 * @ since 3.0 */
public static < E > ImmutableSet < E > copyOf ( E [ ] elements ) { } }

implementation: switch ( elements . length ) { case 0 : return of ( ) ; case 1 : return of ( elements [ 0 ] ) ; default : return constructUnknownDuplication ( elements . length , elements . clone ( ) ) ; }


signature:
public class ImmutableSet { /** * Builds a new open - addressed hash table from the first n objects in elements . */
static Object [ ] rebuildHashTable ( int newTableSize , Object [ ] elements , int n ) { } }

implementation: Object [ ] hashTable = new Object [ newTableSize ] ; int mask = hashTable . length - 1 ; for ( int i = 0 ; i < n ; i ++ ) { Object e = elements [ i ] ; int j0 = Hashing . smear ( e . hashCode ( ) ) ; for ( int j = j0 ; ; j ++ ) { int index = j & mask ; if ( hashTable [ index ] == null ) { hashTable [ index ] = e ; break ; } } } return hashTable ;


signature:
public class ImmutableSet { /** * Returns an array size suitable for the backing array of a hash table that uses open addressing
 * with linear probing in its implementation . The returned size is the smallest power of two that
 * can hold setSize elements with the desired load factor . Always returns at least setSize + 2. */
@ VisibleForTesting static int chooseTableSize ( int setSize ) { } }

implementation:
setSize = Math . max ( setSize , 2 ) ; // Correct the size for open addressing to match desired load factor .
if ( setSize < CUTOFF ) { // Round up to the next highest power of 2.
int tableSize = Integer . highestOneBit ( setSize - 1 ) << 1 ; while ( tableSize * DESIRED_LOAD_FACTOR < setSize ) { tableSize <<= 1 ; } return tableSize ; } // The table can ' t be completely full or we ' ll get infinite reprobes
checkArgument ( setSize < MAX_TABLE_SIZE , "collection too large" ) ; return MAX_TABLE_SIZE ;


signature:
public class ImmutableSet { /** * Checks the whole hash table for poor hash distribution . Takes O ( n ) in the worst case , O ( n / log
 * n ) on average .
 * < p > The online hash flooding detecting in RegularSetBuilderImpl . add can detect e . g . many exactly
 * matching hash codes , which would cause construction to take O ( n ^ 2 ) , but can ' t detect e . g . hash
 * codes adversarially designed to go into ascending table locations , which keeps construction
 * O ( n ) ( as desired ) but then can have O ( n ) queries later .
 * < p > If this returns false , then no query can take more than O ( log n ) .
 * < p > Note that for a RegularImmutableSet with elements with truly random hash codes , contains
 * operations take expected O ( 1 ) time but with high probability take O ( log n ) for at least some
 * element . ( https : / / en . wikipedia . org / wiki / Linear _ probing # Analysis )
 * < p > This method may return { @ code true } up to { @ link # HASH _ FLOODING _ FPP } of the time even on
 * truly random input .
 * < p > If this method returns false , there are definitely no runs of length at least { @ code
 * maxRunBeforeFallback ( hashTable . length ) } nonnull elements . If there are no runs of length at
 * least { @ code maxRunBeforeFallback ( hashTable . length ) / 2 } nonnull elements , this method
 * definitely returns false . In between those constraints , the result of this method is undefined ,
 * subject to the above { @ link # HASH _ FLOODING _ FPP } constraint . */
static boolean hashFloodingDetected ( Object [ ] hashTable ) { } }

implementation:
int maxRunBeforeFallback = maxRunBeforeFallback ( hashTable . length ) ; // Test for a run wrapping around the end of the table of length at least maxRunBeforeFallback .
int endOfStartRun ; for ( endOfStartRun = 0 ; endOfStartRun < hashTable . length ; ) { if ( hashTable [ endOfStartRun ] == null ) { break ; } endOfStartRun ++ ; if ( endOfStartRun > maxRunBeforeFallback ) { return true ; } } int startOfEndRun ; for ( startOfEndRun = hashTable . length - 1 ; startOfEndRun > endOfStartRun ; startOfEndRun -- ) { if ( hashTable [ startOfEndRun ] == null ) { break ; } if ( endOfStartRun + ( hashTable . length - 1 - startOfEndRun ) > maxRunBeforeFallback ) { return true ; } } // Now , break the remainder of the table into blocks of maxRunBeforeFallback / 2 elements and
// check that each has at least one null .
int testBlockSize = maxRunBeforeFallback / 2 ; blockLoop : for ( int i = endOfStartRun + 1 ; i + testBlockSize <= startOfEndRun ; i += testBlockSize ) { for ( int j = 0 ; j < testBlockSize ; j ++ ) { if ( hashTable [ i + j ] == null ) { continue blockLoop ; } } return true ; } return false ;


signature:
public class TopKSelector { /** * Adds { @ code elem } as a candidate for the top { @ code k } elements . This operation takes amortized
 * O ( 1 ) time . */
public void offer ( @ NullableDecl T elem ) { } }

implementation:
if ( k == 0 ) { return ; } else if ( bufferSize == 0 ) { buffer [ 0 ] = elem ; threshold = elem ; bufferSize = 1 ; } else if ( bufferSize < k ) { buffer [ bufferSize ++ ] = elem ; if ( comparator . compare ( elem , threshold ) > 0 ) { threshold = elem ; } } else if ( comparator . compare ( elem , threshold ) < 0 ) { // Otherwise , we can ignore elem ; we ' ve seen k better elements .
buffer [ bufferSize ++ ] = elem ; if ( bufferSize == 2 * k ) { trim ( ) ; } }


signature:
public class ImmutableTable { /** * Returns an empty immutable table . */
@ SuppressWarnings ( "unchecked" ) public static < R , C , V > ImmutableTable < R , C , V > of ( ) { } }

implementation: return ( ImmutableTable < R , C , V > ) SparseImmutableTable . EMPTY ;


signature:
public class ImmutableTable { /** * Returns an immutable table containing a single cell . */
public static < R , C , V > ImmutableTable < R , C , V > of ( R rowKey , C columnKey , V value ) { } }

implementation: return new SingletonImmutableTable < > ( rowKey , columnKey , value ) ;


signature:
public class ImmutableTable { /** * Returns an immutable copy of the provided table .
 * < p > The { @ link Table # cellSet ( ) } iteration order of the provided table determines the iteration
 * ordering of all views in the returned table . Note that some views of the original table and the
 * copied table may have different iteration orders . For more control over the ordering , create a
 * { @ link Builder } and call { @ link Builder # orderRowsBy } , { @ link Builder # orderColumnsBy } , and
 * { @ link Builder # putAll }
 * < 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 . */
public static < R , C , V > ImmutableTable < R , C , V > copyOf ( Table < ? extends R , ? extends C , ? extends V > table ) { } }

implementation: if ( table instanceof ImmutableTable ) { @ SuppressWarnings ( "unchecked" ) ImmutableTable < R , C , V > parameterizedTable = ( ImmutableTable < R , C , V > ) table ; return parameterizedTable ; } else { return copyOf ( table . cellSet ( ) ) ; }


signature:
public class ImmutableTable { /** * Guaranteed to throw an exception and leave the table unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public final V put ( R rowKey , C columnKey , V value ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class ImmutableTable { /** * Guaranteed to throw an exception and leave the table unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public final V remove ( Object rowKey , Object columnKey ) { } }


signature:
public class ForwardingSortedMultiset { /** * A sensible definition of { @ link # pollLastEntry ( ) } in terms of { @ code
 * descendingMultiset ( ) . entrySet ( ) . iterator ( ) } .
 * < p > If you override { @ link # descendingMultiset ( ) } or { @ link # entrySet ( ) } , you may wish to
 * override { @ link # pollLastEntry ( ) } to forward to this implementation . */
protected Entry < E > standardPollLastEntry ( ) { } }

implementation: Iterator < Entry < E > > entryIterator = descendingMultiset ( ) . entrySet ( ) . iterator ( ) ; if ( ! entryIterator . hasNext ( ) ) { return null ; } Entry < E > entry = entryIterator . next ( ) ; entry = Multisets . immutableEntry ( entry . getElement ( ) , entry . getCount ( ) ) ; entryIterator . remove ( ) ; return entry ;


signature:
public class ForwardingSortedMultiset { /** * A sensible definition of { @ link # subMultiset ( Object , BoundType , Object , BoundType ) } in terms of
 * { @ link # headMultiset ( Object , BoundType ) headMultiset } and { @ link # tailMultiset ( Object ,
 * BoundType ) tailMultiset } .
 * < p > If you override either of these methods , you may wish to override { @ link
 * # subMultiset ( Object , BoundType , Object , BoundType ) } to forward to this implementation . */
protected SortedMultiset < E > standardSubMultiset ( E lowerBound , BoundType lowerBoundType , E upperBound , BoundType upperBoundType ) { } }

implementation: return tailMultiset ( lowerBound , lowerBoundType ) . headMultiset ( upperBound , upperBoundType ) ;


signature:
public class MutableTypeToInstanceMap { /** * Not supported . Use { @ link # putInstance } instead .
 * @ deprecated unsupported operation
 * @ throws UnsupportedOperationException always */
@ CanIgnoreReturnValue @ Deprecated @ Override public B put ( TypeToken < ? extends B > key , B value ) { } }

implementation: throw new UnsupportedOperationException ( "Please use putInstance() instead." ) ;


signature:
public class Lists { /** * Returns an unmodifiable list containing the specified first element and backed by the specified
 * array of additional elements . Changes to the { @ code rest } array will be reflected in the
 * returned list . Unlike { @ link Arrays # asList } , the returned list is unmodifiable .
 * < p > This is useful when a varargs method needs to use a signature such as { @ code ( Foo firstFoo ,
 * Foo . . . moreFoos ) } , in order to avoid overload ambiguity or to enforce a minimum argument count .
 * < p > The returned list is serializable and implements { @ link RandomAccess } .
 * @ param first the first element
 * @ param rest an array of additional elements , possibly empty
 * @ return an unmodifiable list containing the specified elements */
public static < E > List < E > asList ( @ Nullable E first , E [ ] rest ) { } }

implementation: return new OnePlusArrayList < > ( first , rest ) ;


signature:
public class Lists { /** * Returns an unmodifiable list containing the specified first and second element , and backed by
 * the specified array of additional elements . Changes to the { @ code rest } array will be reflected
 * in the returned list . Unlike { @ link Arrays # asList } , the returned list is unmodifiable .
 * < p > This is useful when a varargs method needs to use a signature such as { @ code ( Foo firstFoo ,
 * Foo secondFoo , Foo . . . moreFoos ) } , in order to avoid overload ambiguity or to enforce a minimum
 * argument count .
 * < p > The returned list is serializable and implements { @ link RandomAccess } .
 * @ param first the first element
 * @ param second the second element
 * @ param rest an array of additional elements , possibly empty
 * @ return an unmodifiable list containing the specified elements */
public static < E > List < E > asList ( @ Nullable E first , @ Nullable E second , E [ ] rest ) { } }

implementation: return new TwoPlusArrayList < > ( first , second , rest ) ;


signature:
public class Lists { /** * An implementation of { @ link List # equals ( Object ) } . */
static boolean equalsImpl ( List < ? > thisList , @ Nullable Object other ) { } }

implementation:
if ( other == checkNotNull ( thisList ) ) { return true ; } if ( ! ( other instanceof List ) ) { return false ; } List < ? > otherList = ( List < ? > ) other ; int size = thisList . size ( ) ; if ( size != otherList . size ( ) ) { return false ; } if ( thisList instanceof RandomAccess && otherList instanceof RandomAccess ) { // avoid allocation and use the faster loop
for ( int i = 0 ; i < size ; i ++ ) { if ( ! Objects . equal ( thisList . get ( i ) , otherList . get ( i ) ) ) { return false ; } } return true ; } else { return Iterators . elementsEqual ( thisList . iterator ( ) , otherList . iterator ( ) ) ; }


signature:
public class ImmutableSortedAsList { /** * Override indexOf ( ) and lastIndexOf ( ) to be O ( log N ) instead of O ( N ) . */
@ GwtIncompatible // ImmutableSortedSet . indexOf
// TODO ( cpovirk ) : consider manual binary search under GWT to preserve O ( log N ) lookup
@ Override public int indexOf ( @ Nullable Object target ) { } }

implementation:
int index = delegateCollection ( ) . indexOf ( target ) ; // TODO ( kevinb ) : reconsider if it ' s really worth making feeble attempts at
// sanity for inconsistent comparators .
// The equals ( ) check is needed when the comparator isn ' t compatible with
// equals ( ) .
return ( index >= 0 && get ( index ) . equals ( target ) ) ? index : - 1 ;


signature:
public class Converter { /** * Returns a converter whose { @ code convert } method applies { @ code secondConverter } to the result
 * of this converter . Its { @ code reverse } method applies the converters in reverse order .
 * < p > The returned converter is serializable if { @ code this } converter and { @ code secondConverter }
 * are . */
public final < C > Converter < A , C > andThen ( Converter < B , C > secondConverter ) { } }

implementation: return doAndThen ( secondConverter ) ;


signature:
public class Converter { /** * Returns a serializable converter that always converts or reverses an object to itself . */
@ SuppressWarnings ( "unchecked" ) // implementation is " fully variant "
public static < T > Converter < T , T > identity ( ) { } }

implementation: return ( IdentityConverter < T > ) IdentityConverter . INSTANCE ;


signature:
public class AbstractSetMultimap { /** * { @ inheritDoc }
 * < p > Because a { @ code SetMultimap } has unique values for a given key , this method returns a
 * { @ link Set } , instead of the { @ link Collection } specified in the { @ link Multimap } interface . */
@ Override public Set < Entry < K , V > > entries ( ) { } }

implementation: return ( Set < Entry < K , V > > ) super . entries ( ) ;


signature:
public class AbstractSetMultimap { /** * { @ inheritDoc }
 * < p > Because a { @ code SetMultimap } has unique values for a given key , this method returns a
 * { @ link Set } , instead of the { @ link Collection } specified in the { @ link Multimap } interface . */
@ CanIgnoreReturnValue @ Override public Set < V > removeAll ( @ NullableDecl Object key ) { } }

implementation: return ( Set < V > ) super . removeAll ( key ) ;


signature:
public class RegularImmutableTable { /** * A factory that chooses the most space - efficient representation of the table . */
static < R , C , V > RegularImmutableTable < R , C , V > forOrderedComponents ( ImmutableList < Cell < R , C , V > > cellList , ImmutableSet < R > rowSpace , ImmutableSet < C > columnSpace ) { } }

implementation:
// use a dense table if more than half of the cells have values
// TODO ( gak ) : tune this condition based on empirical evidence
return ( cellList . size ( ) > ( ( ( long ) rowSpace . size ( ) * columnSpace . size ( ) ) / 2 ) ) ? new DenseImmutableTable < R , C , V > ( cellList , rowSpace , columnSpace ) : new SparseImmutableTable < R , C , V > ( cellList , rowSpace , columnSpace ) ;


signature:
public class RegularImmutableTable { /** * We could have declared this method ' static ' but the additional compile - time checks achieved by
 * referencing the type variables seem worthwhile . */
final void checkNoDuplicate ( R rowKey , C columnKey , V existingValue , V newValue ) { } }

implementation: checkArgument ( existingValue == null , "Duplicate key: (row=%s, column=%s), values: [%s, %s]." , rowKey , columnKey , newValue , existingValue ) ;


signature:
public class FluentFuture { /** * Converts the given { @ code ListenableFuture } to an equivalent { @ code FluentFuture } .
 * < p > If the given { @ code ListenableFuture } is already a { @ code FluentFuture } , it is returned
 * directly . If not , it is wrapped in a { @ code FluentFuture } that delegates all calls to the
 * original { @ code ListenableFuture } . */
public static < V > FluentFuture < V > from ( ListenableFuture < V > future ) { } }

implementation: return future instanceof FluentFuture ? ( FluentFuture < V > ) future : new ForwardingFluentFuture < V > ( future ) ;


signature:
public class FluentFuture { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since NEXT */
@ Deprecated public static < V > FluentFuture < V > from ( FluentFuture < V > future ) { } }

implementation: return checkNotNull ( future ) ;


signature:
public class FluentFuture { /** * Returns a { @ code Future } whose result is taken from this { @ code Future } or , if this { @ code
 * Future } fails with the given { @ code exceptionType } , from the result provided by the { @ code
 * fallback } . { @ link Function # apply } is not invoked until the primary input has failed , so if the
 * primary input succeeds , it is never invoked . If , during the invocation of { @ code fallback } , an
 * exception is thrown , this exception is used as the result of the output { @ code Future } .
 * < p > Usage example :
 * < pre > { @ code
 * / / Falling back to a zero counter in case an exception happens when processing the RPC to fetch
 * / / counters .
 * ListenableFuture < Integer > faultTolerantFuture =
 * fetchCounters ( ) . catching ( FetchException . class , x - > 0 , directExecutor ( ) ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link # addListener } documentation . All its warnings about heavyweight
 * listeners are also applicable to heavyweight functions passed to this method .
 * < p > This method is similar to { @ link java . util . concurrent . CompletableFuture # exceptionally } . It
 * can also serve some of the use cases of { @ link java . util . concurrent . CompletableFuture # handle }
 * and { @ link java . util . concurrent . CompletableFuture # handleAsync } when used along with { @ link
 * # transform } .
 * @ param exceptionType the exception type that triggers use of { @ code fallback } . The exception
 * type is matched against the input ' s exception . " The input ' s exception " means the cause of
 * the { @ link ExecutionException } thrown by { @ code input . get ( ) } or , if { @ code get ( ) } throws a
 * different kind of exception , that exception itself . To avoid hiding bugs and other
 * unrecoverable errors , callers should prefer more specific types , avoiding { @ code
 * Throwable . class } in particular .
 * @ param fallback the { @ link Function } to be called if the input fails with the expected
 * exception type . The function ' s argument is the input ' s exception . " The input ' s exception "
 * means the cause of the { @ link ExecutionException } thrown by { @ code this . get ( ) } or , if
 * { @ code get ( ) } throws a different kind of exception , that exception itself .
 * @ param executor the executor that runs { @ code fallback } if the input fails */
@ Partially . GwtIncompatible ( "AVAILABLE but requires exceptionType to be Throwable.class" ) public final < X extends Throwable > FluentFuture < V > catching ( Class < X > exceptionType , Function < ? super X , ? extends V > fallback , Executor executor ) { } }

implementation: return ( FluentFuture < V > ) Futures . catching ( this , exceptionType , fallback , executor ) ;


signature:
public class FluentFuture { /** * Returns a { @ code Future } whose result is taken from this { @ code Future } or , if this { @ code
 * Future } fails with the given { @ code exceptionType } , from the result provided by the { @ code
 * fallback } . { @ link AsyncFunction # apply } is not invoked until the primary input has failed , so if
 * the primary input succeeds , it is never invoked . If , during the invocation of { @ code fallback } ,
 * an exception is thrown , this exception is used as the result of the output { @ code Future } .
 * < p > Usage examples :
 * < pre > { @ code
 * / / Falling back to a zero counter in case an exception happens when processing the RPC to fetch
 * / / counters .
 * ListenableFuture < Integer > faultTolerantFuture =
 * fetchCounters ( ) . catchingAsync (
 * FetchException . class , x - > immediateFuture ( 0 ) , directExecutor ( ) ) ;
 * } < / pre >
 * < p > The fallback can also choose to propagate the original exception when desired :
 * < pre > { @ code
 * / / Falling back to a zero counter only in case the exception was a
 * / / TimeoutException .
 * ListenableFuture < Integer > faultTolerantFuture =
 * fetchCounters ( ) . catchingAsync (
 * FetchException . class ,
 * if ( omitDataOnFetchFailure ) {
 * return immediateFuture ( 0 ) ;
 * throw e ;
 * directExecutor ( ) ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link # addListener } documentation . All its warnings about heavyweight
 * listeners are also applicable to heavyweight functions passed to this method . ( Specifically ,
 * { @ code directExecutor } functions should avoid heavyweight operations inside { @ code
 * AsyncFunction . apply } . Any heavyweight operations should occur in other threads responsible for
 * completing the returned { @ code Future } . )
 * < p > This method is similar to { @ link java . util . concurrent . CompletableFuture # exceptionally } . It
 * can also serve some of the use cases of { @ link java . util . concurrent . CompletableFuture # handle }
 * and { @ link java . util . concurrent . CompletableFuture # handleAsync } when used along with { @ link
 * # transform } .
 * @ param exceptionType the exception type that triggers use of { @ code fallback } . The exception
 * type is matched against the input ' s exception . " The input ' s exception " means the cause of
 * the { @ link ExecutionException } thrown by { @ code this . get ( ) } or , if { @ code get ( ) } throws a
 * different kind of exception , that exception itself . To avoid hiding bugs and other
 * unrecoverable errors , callers should prefer more specific types , avoiding { @ code
 * Throwable . class } in particular .
 * @ param fallback the { @ link AsyncFunction } to be called if the input fails with the expected
 * exception type . The function ' s argument is the input ' s exception . " The input ' s exception "
 * means the cause of the { @ link ExecutionException } thrown by { @ code input . get ( ) } or , if
 * { @ code get ( ) } throws a different kind of exception , that exception itself .
 * @ param executor the executor that runs { @ code fallback } if the input fails */
@ Partially . GwtIncompatible ( "AVAILABLE but requires exceptionType to be Throwable.class" ) public final < X extends Throwable > FluentFuture < V > catchingAsync ( Class < X > exceptionType , AsyncFunction < ? super X , ? extends V > fallback , Executor executor ) { } }

implementation: return ( FluentFuture < V > ) Futures . catchingAsync ( this , exceptionType , fallback , executor ) ;


signature:
public class FluentFuture { /** * Returns a future that delegates to this future but will finish early ( via a { @ link
 * TimeoutException } wrapped in an { @ link ExecutionException } ) if the specified timeout expires .
 * If the timeout expires , not only will the output future finish , but also the input future
 * ( { @ code this } ) will be cancelled and interrupted .
 * @ param timeout when to time out the future
 * @ param unit the time unit of the time parameter
 * @ param scheduledExecutor The executor service to enforce the timeout . */
@ GwtIncompatible // ScheduledExecutorService
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public final FluentFuture < V > withTimeout ( long timeout , TimeUnit unit , ScheduledExecutorService scheduledExecutor ) { } }

implementation: return ( FluentFuture < V > ) Futures . withTimeout ( this , timeout , unit , scheduledExecutor ) ;


signature:
public class FluentFuture { /** * Returns a new { @ code Future } whose result is asynchronously derived from the result of this
 * { @ code Future } . If the input { @ code Future } fails , the returned { @ code Future } fails with the
 * same exception ( and the function is not invoked ) .
 * < p > More precisely , the returned { @ code Future } takes its result from a { @ code Future } produced
 * by applying the given { @ code AsyncFunction } to the result of the original { @ code Future } .
 * Example usage :
 * < pre > { @ code
 * FluentFuture < RowKey > rowKeyFuture = FluentFuture . from ( indexService . lookUp ( query ) ) ;
 * ListenableFuture < QueryResult > queryFuture =
 * rowKeyFuture . transformAsync ( dataService : : readFuture , executor ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link # addListener } documentation . All its warnings about heavyweight
 * listeners are also applicable to heavyweight functions passed to this method . ( Specifically ,
 * { @ code directExecutor } functions should avoid heavyweight operations inside { @ code
 * AsyncFunction . apply } . Any heavyweight operations should occur in other threads responsible for
 * completing the returned { @ code Future } . )
 * < p > The returned { @ code Future } attempts to keep its cancellation state in sync with that of the
 * input future and that of the future returned by the chain function . That is , if the returned
 * { @ code Future } is cancelled , it will attempt to cancel the other two , and if either of the
 * other two is cancelled , the returned { @ code Future } will receive a callback in which it will
 * attempt to cancel itself .
 * < p > This method is similar to { @ link java . util . concurrent . CompletableFuture # thenCompose } and
 * { @ link java . util . concurrent . CompletableFuture # thenComposeAsync } . It can also serve some of the
 * use cases of { @ link java . util . concurrent . CompletableFuture # handle } and { @ link
 * java . util . concurrent . CompletableFuture # handleAsync } when used along with { @ link # catching } .
 * @ param function A function to transform the result of this future to the result of the output
 * future
 * @ param executor Executor to run the function in .
 * @ return A future that holds result of the function ( if the input succeeded ) or the original
 * input ' s failure ( if not ) */
public final < T > FluentFuture < T > transformAsync ( AsyncFunction < ? super V , T > function , Executor executor ) { } }

implementation: return ( FluentFuture < T > ) Futures . transformAsync ( this , function , executor ) ;


signature:
public class FluentFuture { /** * Returns a new { @ code Future } whose result is derived from the result of this { @ code Future } . If
 * this input { @ code Future } fails , the returned { @ code Future } fails with the same exception ( and
 * the function is not invoked ) . Example usage :
 * < pre > { @ code
 * ListenableFuture < List < Row > > rowsFuture =
 * queryFuture . transform ( QueryResult : : getRows , executor ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link # addListener } documentation . All its warnings about heavyweight
 * listeners are also applicable to heavyweight functions passed to this method .
 * < p > The returned { @ code Future } attempts to keep its cancellation state in sync with that of the
 * input future . That is , if the returned { @ code Future } is cancelled , it will attempt to cancel
 * the input , and if the input is cancelled , the returned { @ code Future } will receive a callback
 * in which it will attempt to cancel itself .
 * < p > An example use of this method is to convert a serializable object returned from an RPC into
 * a POJO .
 * < p > This method is similar to { @ link java . util . concurrent . CompletableFuture # thenApply } and
 * { @ link java . util . concurrent . CompletableFuture # thenApplyAsync } . It can also serve some of the
 * use cases of { @ link java . util . concurrent . CompletableFuture # handle } and { @ link
 * java . util . concurrent . CompletableFuture # handleAsync } when used along with { @ link # catching } .
 * @ param function A Function to transform the results of this future to the results of the
 * returned future .
 * @ param executor Executor to run the function in .
 * @ return A future that holds result of the transformation . */
public final < T > FluentFuture < T > transform ( Function < ? super V , T > function , Executor executor ) { } }

implementation: return ( FluentFuture < T > ) Futures . transform ( this , function , executor ) ;


signature:
public class FluentFuture { /** * Registers separate success and failure callbacks to be run when this { @ code Future } ' s
 * computation is { @ linkplain java . util . concurrent . Future # isDone ( ) complete } or , if the
 * computation is already complete , immediately .
 * < p > The callback is run on { @ code executor } . There is no guaranteed ordering of execution of
 * callbacks , but any callback added through this method is guaranteed to be called once the
 * computation is complete .
 * < p > Example :
 * < pre > { @ code
 * future . addCallback (
 * new FutureCallback < QueryResult > ( ) {
 * public void onSuccess ( QueryResult result ) {
 * storeInCache ( result ) ;
 * public void onFailure ( Throwable t ) {
 * reportError ( t ) ;
 * } , executor ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link # addListener } documentation . All its warnings about heavyweight
 * listeners are also applicable to heavyweight callbacks passed to this method .
 * < p > For a more general interface to attach a completion listener , see { @ link # addListener } .
 * < p > This method is similar to { @ link java . util . concurrent . CompletableFuture # whenComplete } and
 * { @ link java . util . concurrent . CompletableFuture # whenCompleteAsync } . It also serves the use case
 * of { @ link java . util . concurrent . CompletableFuture # thenAccept } and { @ link
 * java . util . concurrent . CompletableFuture # thenAcceptAsync } .
 * @ param callback The callback to invoke when this { @ code Future } is completed .
 * @ param executor The executor to run { @ code callback } when the future completes . */
public final void addCallback ( FutureCallback < ? super V > callback , Executor executor ) { } }

implementation: Futures . addCallback ( this , callback , executor ) ;


signature:
public class ImmutableGraph { /** * Returns an immutable copy of { @ code graph } . */
public static < N > ImmutableGraph < N > copyOf ( Graph < N > graph ) { } }

implementation: return ( graph instanceof ImmutableGraph ) ? ( ImmutableGraph < N > ) graph : new ImmutableGraph < N > ( new ConfigurableValueGraph < N , Presence > ( GraphBuilder . from ( graph ) , getNodeConnections ( graph ) , graph . edges ( ) . size ( ) ) ) ;


signature:
public class ImmutableGraph { /** * Simply returns its argument .
 * @ deprecated no need to use this */
@ Deprecated public static < N > ImmutableGraph < N > copyOf ( ImmutableGraph < N > graph ) { } }

implementation: return checkNotNull ( graph ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing a single element . */
public static < E extends Comparable < ? super E > > ImmutableSortedMultiset < E > of ( E element ) { } }

implementation: RegularImmutableSortedSet < E > elementSet = ( RegularImmutableSortedSet < E > ) ImmutableSortedSet . of ( element ) ; long [ ] cumulativeCounts = { 0 , 1 } ; return new RegularImmutableSortedMultiset < E > ( elementSet , cumulativeCounts , 0 , 1 ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by their natural
 * ordering .
 * @ throws NullPointerException if any element is null */
@ SuppressWarnings ( "unchecked" ) public static < E extends Comparable < ? super E > > ImmutableSortedMultiset < E > of ( E e1 , E e2 ) { } }

implementation: return copyOf ( Ordering . natural ( ) , Arrays . asList ( e1 , e2 ) ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by their natural
 * ordering .
 * @ throws NullPointerException if any element is null */
@ SuppressWarnings ( "unchecked" ) public static < E extends Comparable < ? super E > > ImmutableSortedMultiset < E > of ( E e1 , E e2 , E e3 , E e4 , E e5 , E e6 , E ... remaining ) { } }

implementation: int size = remaining . length + 6 ; List < E > all = Lists . newArrayListWithCapacity ( size ) ; Collections . addAll ( all , e1 , e2 , e3 , e4 , e5 , e6 ) ; Collections . addAll ( all , remaining ) ; return copyOf ( Ordering . natural ( ) , all ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by their natural
 * ordering .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E extends Comparable < ? super E > > ImmutableSortedMultiset < E > copyOf ( E [ ] elements ) { } }

implementation: return copyOf ( Ordering . natural ( ) , Arrays . asList ( elements ) ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by their natural
 * ordering . To create a copy of a { @ code SortedMultiset } that preserves the comparator , call
 * { @ link # copyOfSorted } instead . This method iterates over { @ code elements } at most once .
 * < p > Note that if { @ code s } is a { @ code Multiset < String > } , then { @ code
 * ImmutableSortedMultiset . copyOf ( s ) } returns an { @ code ImmutableSortedMultiset < String > }
 * containing each of the strings in { @ code s } , while { @ code ImmutableSortedMultiset . of ( s ) }
 * returns an { @ code ImmutableSortedMultiset < Multiset < String > > } containing one element ( the given
 * multiset itself ) .
 * < 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 .
 * < p > This method is not type - safe , as it may be called on elements that are not mutually
 * comparable .
 * @ throws ClassCastException if the elements are not mutually comparable
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableSortedMultiset < E > copyOf ( Iterable < ? extends E > elements ) { } }

implementation:
// Hack around E not being a subtype of Comparable .
// Unsafe , see ImmutableSortedMultisetFauxverideShim .
@ SuppressWarnings ( "unchecked" ) Ordering < E > naturalOrder = ( Ordering < E > ) Ordering . < Comparable > natural ( ) ; return copyOf ( naturalOrder , elements ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by the given { @ code
 * Comparator } .
 * @ throws NullPointerException if { @ code comparator } or any of { @ code elements } is null */
public static < E > ImmutableSortedMultiset < E > copyOf ( Comparator < ? super E > comparator , Iterator < ? extends E > elements ) { } }

implementation: checkNotNull ( comparator ) ; return new Builder < E > ( comparator ) . addAll ( elements ) . build ( ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the given elements sorted by the given { @ code
 * Comparator } . This method iterates over { @ code elements } at most once .
 * < 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 { @ code comparator } or any of { @ code elements } is null */
@ SuppressWarnings ( "unchecked" ) public static < E > ImmutableSortedMultiset < E > copyOf ( Comparator < ? super E > comparator , Iterable < ? extends E > elements ) { } }

implementation:
if ( elements instanceof ImmutableSortedMultiset ) { @ SuppressWarnings ( "unchecked" ) // immutable collections are always safe for covariant casts
ImmutableSortedMultiset < E > multiset = ( ImmutableSortedMultiset < E > ) elements ; if ( comparator . equals ( multiset . comparator ( ) ) ) { if ( multiset . isPartialView ( ) ) { return copyOfSortedEntries ( comparator , multiset . entrySet ( ) . asList ( ) ) ; } else { return multiset ; } } } return new ImmutableSortedMultiset . Builder < E > ( comparator ) . addAll ( elements ) . build ( ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns an immutable sorted multiset containing the elements of a sorted multiset , sorted by
 * the same { @ code Comparator } . That behavior differs from { @ link # copyOf ( Iterable ) } , which always
 * uses the natural ordering of the elements .
 * < 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 .
 * < p > This method is safe to use even when { @ code sortedMultiset } is a synchronized or concurrent
 * collection that is currently being modified by another thread .
 * @ throws NullPointerException if { @ code sortedMultiset } or any of its elements is null */
public static < E > ImmutableSortedMultiset < E > copyOfSorted ( SortedMultiset < E > sortedMultiset ) { } }

implementation: return copyOfSortedEntries ( sortedMultiset . comparator ( ) , Lists . newArrayList ( sortedMultiset . entrySet ( ) ) ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns a builder that creates immutable sorted multisets with an explicit comparator . If the
 * comparator has a more general type than the set being generated , such as creating a { @ code
 * SortedMultiset < Integer > } with a { @ code Comparator < Number > } , use the { @ link Builder } constructor
 * instead .
 * @ throws NullPointerException if { @ code comparator } is null */
public static < E > Builder < E > orderedBy ( Comparator < E > comparator ) { } }

implementation: return new Builder < E > ( comparator ) ;


signature:
public class ImmutableSortedMultiset { /** * Returns a builder that creates immutable sorted multisets whose elements are ordered by the
 * reverse of their natural ordering .
 * < p > Note : the type parameter { @ code E } extends { @ code Comparable < ? > } rather than { @ code
 * Comparable < ? super E > } as a workaround for javac < a
 * href = " http : / / bugs . sun . com / bugdatabase / view _ bug . do ? bug _ id = 6468354 " > bug 6468354 < / a > . */
public static < E extends Comparable < ? > > Builder < E > reverseOrder ( ) { } }

implementation: return new Builder < E > ( Ordering . natural ( ) . reverse ( ) ) ;


signature:
public class ForwardingCollection { /** * A sensible definition of { @ link # remove } in terms of { @ link # iterator } , using the iterator ' s
 * { @ code remove } method . If you override { @ link # iterator } , you may wish to override { @ link
 * # remove } to forward to this implementation .
 * @ since 7.0 */
protected boolean standardRemove ( @ Nullable Object object ) { } }

implementation: Iterator < E > iterator = iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( Objects . equal ( iterator . next ( ) , object ) ) { iterator . remove ( ) ; return true ; } } return false ;


signature:
public class Multisets { /** * Returns a { @ code Collector } that accumulates elements into a multiset created via the specified
 * { @ code Supplier } , 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 .
 * Elements are added in encounter order .
 * < p > If the mapped elements contain duplicates ( according to { @ link Object # equals } ) , the element
 * will be added more than once , with the count summed over all appearances of the element .
 * < p > Note that { @ code stream . collect ( toMultiset ( function , e - > 1 , supplier ) ) } is equivalent to
 * { @ code stream . map ( function ) . collect ( Collectors . toCollection ( supplier ) ) } .
 * @ since 22.0 */
public static < T , E , M extends Multiset < E > > Collector < T , ? , M > toMultiset ( java . util . function . Function < ? super T , E > elementFunction , java . util . function . ToIntFunction < ? super T > countFunction , java . util . function . Supplier < M > multisetSupplier ) { } }

implementation: checkNotNull ( elementFunction ) ; checkNotNull ( countFunction ) ; checkNotNull ( multisetSupplier ) ; return Collector . of ( multisetSupplier , ( ms , t ) -> ms . add ( elementFunction . apply ( t ) , countFunction . applyAsInt ( t ) ) , ( ms1 , ms2 ) -> { ms1 . addAll ( ms2 ) ; return ms1 ; } ) ;


signature:
public class Multisets { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < E > Multiset < E > unmodifiableMultiset ( ImmutableMultiset < E > multiset ) { } }

implementation: return checkNotNull ( multiset ) ;


signature:
public class Multisets { /** * Returns an unmodifiable view of the specified sorted multiset . Query operations on the returned
 * multiset " read through " to the specified multiset , and attempts to modify the returned multiset
 * result in an { @ link UnsupportedOperationException } .
 * < p > The returned multiset will be serializable if the specified multiset is serializable .
 * @ param sortedMultiset the sorted multiset for which an unmodifiable view is to be generated
 * @ return an unmodifiable view of the multiset
 * @ since 11.0 */
@ Beta public static < E > SortedMultiset < E > unmodifiableSortedMultiset ( SortedMultiset < E > sortedMultiset ) { } }

implementation:
// it ' s in its own file so it can be emulated for GWT
return new UnmodifiableSortedMultiset < E > ( checkNotNull ( sortedMultiset ) ) ;


signature:
public class Multisets { /** * Returns an immutable multiset entry with the specified element and count . The entry will be
 * serializable if { @ code e } is .
 * @ param e the element to be associated with the returned entry
 * @ param n the count to be associated with the returned entry
 * @ throws IllegalArgumentException if { @ code n } is negative */
public static < E > Multiset . Entry < E > immutableEntry ( @ Nullable E e , int n ) { } }

implementation: return new ImmutableEntry < E > ( e , n ) ;


signature:
public class Multisets { /** * Returns a view of the elements of { @ code unfiltered } that satisfy a predicate . The returned
 * multiset is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting multiset ' s iterators , and those of its { @ code entrySet ( ) } and { @ code
 * elementSet ( ) } , do not support { @ code remove ( ) } . However , all other multiset methods supported
 * by { @ code unfiltered } are supported by the returned multiset . When given an element that
 * doesn ' t satisfy the predicate , the multiset ' s { @ code add ( ) } and { @ code addAll ( ) } methods throw
 * an { @ link IllegalArgumentException } . When methods such as { @ code removeAll ( ) } and { @ code
 * clear ( ) } are called on the filtered multiset , only elements that satisfy the filter will be
 * removed from the underlying multiset .
 * < p > The returned multiset isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered multiset ' s methods , such as { @ code size ( ) } , iterate across every
 * element in the underlying multiset and determine which elements satisfy the filter . When a live
 * view is < i > not < / i > needed , it may be faster to copy the returned multiset and use the copy .
 * < p > < b > Warning : < / b > { @ code predicate } must be < i > consistent with equals < / i > , as documented at
 * { @ link Predicate # apply } . Do not provide a predicate such as { @ code
 * Predicates . instanceOf ( ArrayList . class ) } , which is inconsistent with equals . ( See { @ link
 * Iterables # filter ( Iterable , Class ) } for related functionality . )
 * @ since 14.0 */
@ Beta public static < E > Multiset < E > filter ( Multiset < E > unfiltered , Predicate < ? super E > predicate ) { } }

implementation:
if ( unfiltered instanceof FilteredMultiset ) { // Support clear ( ) , removeAll ( ) , and retainAll ( ) when filtering a filtered
// collection .
FilteredMultiset < E > filtered = ( FilteredMultiset < E > ) unfiltered ; Predicate < E > combinedPredicate = Predicates . < E > and ( filtered . predicate , predicate ) ; return new FilteredMultiset < E > ( filtered . unfiltered , combinedPredicate ) ; } return new FilteredMultiset < E > ( unfiltered , predicate ) ;


signature:
public class Multisets { /** * Returns an unmodifiable view of the difference of two multisets . In the returned multiset , the
 * count of each element is the result of the < i > zero - truncated subtraction < / i > of its count in
 * the second multiset from its count in the first multiset , with elements that would have a count
 * of 0 not included . The iteration order of the returned multiset matches that of the element set
 * of { @ code multiset1 } , with repeated occurrences of the same element appearing consecutively .
 * < p > Results are undefined if { @ code multiset1 } and { @ code multiset2 } are based on different
 * equivalence relations ( as { @ code HashMultiset } and { @ code TreeMultiset } are ) .
 * @ since 14.0 */
@ Beta public static < E > Multiset < E > difference ( final Multiset < E > multiset1 , final Multiset < ? > multiset2 ) { } }

implementation:
checkNotNull ( multiset1 ) ; checkNotNull ( multiset2 ) ; // TODO ( lowasser ) : consider making the entries live views
return new ViewMultiset < E > ( ) { @ Override public int count ( @ Nullable Object element ) { int count1 = multiset1 . count ( element ) ; return ( count1 == 0 ) ? 0 : Math . max ( 0 , count1 - multiset2 . count ( element ) ) ; } @ Override public void clear ( ) { throw new UnsupportedOperationException ( ) ; } @ Override Iterator < E > elementIterator ( ) { final Iterator < Entry < E > > iterator1 = multiset1 . entrySet ( ) . iterator ( ) ; return new AbstractIterator < E > ( ) { @ Override protected E computeNext ( ) { while ( iterator1 . hasNext ( ) ) { Entry < E > entry1 = iterator1 . next ( ) ; E element = entry1 . getElement ( ) ; if ( entry1 . getCount ( ) > multiset2 . count ( element ) ) { return element ; } } return endOfData ( ) ; } } ; } @ Override Iterator < Entry < E > > entryIterator ( ) { final Iterator < Entry < E > > iterator1 = multiset1 . entrySet ( ) . iterator ( ) ; return new AbstractIterator < Entry < E > > ( ) { @ Override protected Entry < E > computeNext ( ) { while ( iterator1 . hasNext ( ) ) { Entry < E > entry1 = iterator1 . next ( ) ; E element = entry1 . getElement ( ) ; int count = entry1 . getCount ( ) - multiset2 . count ( element ) ; if ( count > 0 ) { return immutableEntry ( element , count ) ; } } return endOfData ( ) ; } } ; } @ Override int distinctElements ( ) { return Iterators . size ( entryIterator ( ) ) ; } } ;


signature:
public class Multisets { /** * Delegate implementation which cares about the element type . */
private static < E > boolean retainOccurrencesImpl ( Multiset < E > multisetToModify , Multiset < ? > occurrencesToRetain ) { } }

implementation:
checkNotNull ( multisetToModify ) ; checkNotNull ( occurrencesToRetain ) ; // Avoiding ConcurrentModificationExceptions is tricky .
Iterator < Entry < E > > entryIterator = multisetToModify . entrySet ( ) . iterator ( ) ; boolean changed = false ; while ( entryIterator . hasNext ( ) ) { Entry < E > entry = entryIterator . next ( ) ; int retainCount = occurrencesToRetain . count ( entry . getElement ( ) ) ; if ( retainCount == 0 ) { entryIterator . remove ( ) ; changed = true ; } else if ( retainCount < entry . getCount ( ) ) { multisetToModify . setCount ( entry . getElement ( ) , retainCount ) ; changed = true ; } } return changed ;


signature:
public class Multisets { /** * For each occurrence of an element { @ code e } in { @ code occurrencesToRemove } , removes one
 * occurrence of { @ code e } in { @ code multisetToModify } .
 * < p > Equivalently , this method modifies { @ code multisetToModify } so that { @ code
 * multisetToModify . count ( e ) } is set to { @ code Math . max ( 0 , multisetToModify . count ( e ) -
 * Iterables . frequency ( occurrencesToRemove , e ) ) } .
 * < p > This is < i > not < / i > the same as { @ code multisetToModify . } { @ link Multiset # removeAll
 * removeAll } { @ code ( occurrencesToRemove ) } , which removes all occurrences of elements that appear
 * in { @ code occurrencesToRemove } . However , this operation < i > is < / i > equivalent to , albeit
 * sometimes more efficient than , the following :
 * < pre > { @ code
 * for ( E e : occurrencesToRemove ) {
 * multisetToModify . remove ( e ) ;
 * } < / pre >
 * @ return { @ code true } if { @ code multisetToModify } was changed as a result of this operation
 * @ since 18.0 ( present in 10.0 with a requirement that the second parameter be a { @ code
 * Multiset } ) */
@ CanIgnoreReturnValue public static boolean removeOccurrences ( Multiset < ? > multisetToModify , Iterable < ? > occurrencesToRemove ) { } }

implementation: if ( occurrencesToRemove instanceof Multiset ) { return removeOccurrences ( multisetToModify , ( Multiset < ? > ) occurrencesToRemove ) ; } else { checkNotNull ( multisetToModify ) ; checkNotNull ( occurrencesToRemove ) ; boolean changed = false ; for ( Object o : occurrencesToRemove ) { changed |= multisetToModify . remove ( o ) ; } return changed ; }