signature:
public class Collections2 { /** * Delegates to { @ link Collection # remove } . Returns { @ code false } if the { @ code remove } method
 * throws a { @ code ClassCastException } or { @ code NullPointerException } . */
static boolean safeRemove ( Collection < ? > collection , @ Nullable Object object ) { } }

implementation: checkNotNull ( collection ) ; try { return collection . remove ( object ) ; } catch ( ClassCastException | NullPointerException e ) { return false ; }


signature:
public class Collections2 { /** * Returns { @ code true } if the second list is a permutation of the first . */
private static boolean isPermutation ( List < ? > first , List < ? > second ) { } }

implementation: if ( first . size ( ) != second . size ( ) ) { return false ; } Multiset < ? > firstMultiset = HashMultiset . create ( first ) ; Multiset < ? > secondMultiset = HashMultiset . create ( second ) ; return firstMultiset . equals ( secondMultiset ) ;


signature:
public class Hashing { /** * Returns a general - purpose , < b > temporary - use < / b > , non - cryptographic hash function . The algorithm
 * the returned function implements is unspecified and subject to change without notice .
 * < p > < b > Warning : < / b > a new random seed for these functions is chosen each time the { @ code
 * Hashing } class is loaded . < b > Do not use this method < / b > if hash codes may escape the current
 * process in any way , for example being sent over RPC , or saved to disk . For a general - purpose ,
 * non - cryptographic hash function that will never change behavior , we suggest { @ link
 * # murmur3_128 } .
 * < p > Repeated calls to this method on the same loaded { @ code Hashing } class , using the same value
 * for { @ code minimumBits } , will return identically - behaving { @ link HashFunction } instances .
 * @ param minimumBits a positive integer ( can be arbitrarily large )
 * @ return a hash function , described above , that produces hash codes of length { @ code
 * minimumBits } or greater */
public static HashFunction goodFastHash ( int minimumBits ) { } }

implementation:
int bits = checkPositiveAndMakeMultipleOf32 ( minimumBits ) ; if ( bits == 32 ) { return Murmur3_32HashFunction . GOOD_FAST_HASH_32 ; } if ( bits <= 128 ) { return Murmur3_128HashFunction . GOOD_FAST_HASH_128 ; } // Otherwise , join together some 128 - bit murmur3s
int hashFunctionsNeeded = ( bits + 127 ) / 128 ; HashFunction [ ] hashFunctions = new HashFunction [ hashFunctionsNeeded ] ; hashFunctions [ 0 ] = Murmur3_128HashFunction . GOOD_FAST_HASH_128 ; int seed = GOOD_FAST_HASH_SEED ; for ( int i = 1 ; i < hashFunctionsNeeded ; i ++ ) { seed += 1500450271 ; // a prime ; shouldn ' t matter
hashFunctions [ i ] = murmur3_128 ( seed ) ; } return new ConcatenatedHashFunction ( hashFunctions ) ;


signature:
public class Hashing { /** * Assigns to { @ code input } a " bucket " in the range { @ code [ 0 , buckets ) } , in a uniform manner that
 * minimizes the need for remapping as { @ code buckets } grows . That is , { @ code consistentHash ( h ,
 * n ) } equals :
 * < ul >
 * < li > { @ code n - 1 } , with approximate probability { @ code 1 / n }
 * < li > { @ code consistentHash ( h , n - 1 ) } , otherwise ( probability { @ code 1 - 1 / n } )
 * < / ul >
 * < p > This method is suitable for the common use case of dividing work among buckets that meet the
 * following conditions :
 * < ul >
 * < li > You want to assign the same fraction of inputs to each bucket .
 * < li > When you reduce the number of buckets , you can accept that the most recently added
 * buckets will be removed first . More concretely , if you are dividing traffic among tasks ,
 * you can decrease the number of tasks from 15 and 10 , killing off the final 5 tasks , and
 * { @ code consistentHash } will handle it . If , however , you are dividing traffic among
 * servers { @ code alpha } , { @ code bravo } , and { @ code charlie } and you occasionally need to
 * take each of the servers offline , { @ code consistentHash } will be a poor fit : It provides
 * no way for you to specify which of the three buckets is disappearing . Thus , if your
 * buckets change from { @ code [ alpha , bravo , charlie ] } to { @ code [ bravo , charlie ] } , it will
 * assign all the old { @ code alpha } traffic to { @ code bravo } and all the old { @ code bravo }
 * traffic to { @ code charlie } , rather than letting { @ code bravo } keep its traffic .
 * < / ul >
 * < p > See the < a href = " http : / / en . wikipedia . org / wiki / Consistent _ hashing " > Wikipedia article on
 * consistent hashing < / a > for more information . */
public static int consistentHash ( long input , int buckets ) { } }

implementation:
checkArgument ( buckets > 0 , "buckets must be positive: %s" , buckets ) ; LinearCongruentialGenerator generator = new LinearCongruentialGenerator ( input ) ; int candidate = 0 ; int next ; // Jump from bucket to bucket until we go out of range
while ( true ) { next = ( int ) ( ( candidate + 1 ) / generator . nextDouble ( ) ) ; if ( next >= 0 && next < buckets ) { candidate = next ; } else { return candidate ; } }


signature:
public class Hashing { /** * Returns a hash function which computes its hash code by concatenating the hash codes of the
 * underlying hash functions together . This can be useful if you need to generate hash codes of a
 * specific length .
 * < p > For example , if you need 1024 - bit hash codes , you could join two { @ link Hashing # sha512 } hash
 * functions together : { @ code Hashing . concatenating ( Hashing . sha512 ( ) , Hashing . sha512 ( ) ) } .
 * @ since 19.0 */
public static HashFunction concatenating ( HashFunction first , HashFunction second , HashFunction ... rest ) { } }

implementation:
// We can ' t use Lists . asList ( ) here because there ' s no hash - > collect dependency
List < HashFunction > list = new ArrayList < > ( ) ; list . add ( first ) ; list . add ( second ) ; list . addAll ( Arrays . asList ( rest ) ) ; return new ConcatenatedHashFunction ( list . toArray ( new HashFunction [ 0 ] ) ) ;


signature:
public class CompactHashMap { /** * Creates a fresh entry with the specified object at the specified position in the entry arrays . */
void insertEntry ( int entryIndex , @ Nullable K key , @ Nullable V value , int hash ) { } }

implementation: this . entries [ entryIndex ] = ( ( long ) hash << 32 ) | ( NEXT_MASK & UNSET ) ; this . keys [ entryIndex ] = key ; this . values [ entryIndex ] = value ;


signature:
public class ImmutableSetMultimap { /** * Returns a { @ code Collector } accumulating entries into an { @ code ImmutableSetMultimap } . Each
 * input element is mapped to a key and a stream of values , each of which are put into the
 * resulting { @ code Multimap } , in the encounter order of the stream and the encounter order of the
 * streams of values .
 * < p > Example :
 * < pre > { @ code
 * static final ImmutableSetMultimap < Character , Character > FIRST _ LETTER _ MULTIMAP =
 * Stream . of ( " banana " , " apple " , " carrot " , " asparagus " , " cherry " )
 * . collect (
 * flatteningToImmutableSetMultimap (
 * str - > str . charAt ( 0 ) ,
 * str - > str . substring ( 1 ) . chars ( ) . mapToObj ( c - > ( char ) c ) ) ;
 * / / is equivalent to
 * static final ImmutableSetMultimap < Character , Character > FIRST _ LETTER _ MULTIMAP =
 * ImmutableSetMultimap . < Character , Character > builder ( )
 * . putAll ( ' b ' , Arrays . asList ( ' a ' , ' n ' , ' a ' , ' n ' , ' a ' ) )
 * . putAll ( ' a ' , Arrays . asList ( ' p ' , ' p ' , ' l ' , ' e ' ) )
 * . putAll ( ' c ' , Arrays . asList ( ' a ' , ' r ' , ' r ' , ' o ' , ' t ' ) )
 * . putAll ( ' a ' , Arrays . asList ( ' s ' , ' p ' , ' a ' , ' r ' , ' a ' , ' g ' , ' u ' , ' s ' ) )
 * . putAll ( ' c ' , Arrays . asList ( ' h ' , ' e ' , ' r ' , ' r ' , ' y ' ) )
 * . build ( ) ;
 * / / after deduplication , the resulting multimap is equivalent to
 * static final ImmutableSetMultimap < Character , Character > FIRST _ LETTER _ MULTIMAP =
 * ImmutableSetMultimap . < Character , Character > builder ( )
 * . putAll ( ' b ' , Arrays . asList ( ' a ' , ' n ' ) )
 * . putAll ( ' a ' , Arrays . asList ( ' p ' , ' l ' , ' e ' , ' s ' , ' a ' , ' r ' , ' g ' , ' u ' ) )
 * . putAll ( ' c ' , Arrays . asList ( ' a ' , ' r ' , ' o ' , ' t ' , ' h ' , ' e ' , ' y ' ) )
 * . build ( ) ;
 * } < / pre >
 * @ since 21.0 */
public static < T , K , V > Collector < T , ? , ImmutableSetMultimap < K , V > > flatteningToImmutableSetMultimap ( Function < ? super T , ? extends K > keyFunction , Function < ? super T , ? extends Stream < ? extends V > > valuesFunction ) { } }

implementation: checkNotNull ( keyFunction ) ; checkNotNull ( valuesFunction ) ; return Collectors . collectingAndThen ( Multimaps . flatteningToMultimap ( input -> checkNotNull ( keyFunction . apply ( input ) ) , input -> valuesFunction . apply ( input ) . peek ( Preconditions :: checkNotNull ) , MultimapBuilder . linkedHashKeys ( ) . linkedHashSetValues ( ) :: < K , V > build ) , ImmutableSetMultimap :: copyOf ) ;


signature:
public class ImmutableSetMultimap { /** * Creates an ImmutableSetMultimap from an asMap . entrySet . */
static < K , V > ImmutableSetMultimap < K , V > fromMapEntries ( Collection < ? extends Map . Entry < ? extends K , ? extends Collection < ? extends V > > > mapEntries , @ Nullable Comparator < ? super V > valueComparator ) { } }

implementation: if ( mapEntries . isEmpty ( ) ) { return of ( ) ; } ImmutableMap . Builder < K , ImmutableSet < V > > builder = new ImmutableMap . Builder < > ( mapEntries . size ( ) ) ; int size = 0 ; for ( Entry < ? extends K , ? extends Collection < ? extends V > > entry : mapEntries ) { K key = entry . getKey ( ) ; Collection < ? extends V > values = entry . getValue ( ) ; ImmutableSet < V > set = valueSet ( valueComparator , values ) ; if ( ! set . isEmpty ( ) ) { builder . put ( key , set ) ; size += set . size ( ) ; } } return new ImmutableSetMultimap < > ( builder . build ( ) , size , valueComparator ) ;


signature:
public class ImmutableSetMultimap { /** * Returns an immutable set of the values for the given key . If no mappings in the multimap have
 * the provided key , an empty immutable set is returned . The values are in the same order as the
 * parameters used to build this multimap . */
@ Override public ImmutableSet < V > get ( @ Nullable K key ) { } }

implementation:
// This cast is safe as its type is known in constructor .
ImmutableSet < V > set = ( ImmutableSet < V > ) map . get ( key ) ; return MoreObjects . firstNonNull ( set , emptySet ) ;


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

implementation: return new RegularImmutableSortedSet < E > ( ImmutableList . of ( element ) , Ordering . natural ( ) ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by their natural ordering .
 * When multiple elements are equivalent according to { @ link Comparable # compareTo } , only the first
 * one specified is included .
 * @ throws NullPointerException if any element is null */
@ SuppressWarnings ( "unchecked" ) public static < E extends Comparable < ? super E > > ImmutableSortedSet < E > of ( E e1 , E e2 ) { } }

implementation: return construct ( Ordering . natural ( ) , 2 , e1 , e2 ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by their natural ordering .
 * When multiple elements are equivalent according to { @ link Comparable # compareTo } , only the first
 * one specified is included .
 * @ throws NullPointerException if any element is null
 * @ since 3.0 ( source - compatible since 2.0) */
@ SuppressWarnings ( "unchecked" ) public static < E extends Comparable < ? super E > > ImmutableSortedSet < E > of ( E e1 , E e2 , E e3 , E e4 , E e5 , E e6 , E ... remaining ) { } }

implementation: Comparable [ ] contents = new Comparable [ 6 + remaining . length ] ; contents [ 0 ] = e1 ; contents [ 1 ] = e2 ; contents [ 2 ] = e3 ; contents [ 3 ] = e4 ; contents [ 4 ] = e5 ; contents [ 5 ] = e6 ; System . arraycopy ( remaining , 0 , contents , 6 , remaining . length ) ; return construct ( Ordering . natural ( ) , contents . length , ( E [ ] ) contents ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by their natural ordering .
 * When multiple elements are equivalent according to { @ link Comparable # compareTo } , only the first
 * one specified is included .
 * @ throws NullPointerException if any of { @ code elements } is null
 * @ since 3.0 */
public static < E extends Comparable < ? super E > > ImmutableSortedSet < E > copyOf ( E [ ] elements ) { } }

implementation: return construct ( Ordering . natural ( ) , elements . length , elements . clone ( ) ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by the given { @ code
 * Comparator } . When multiple elements are equivalent according to { @ code compareTo ( ) } , only the
 * first one specified is included .
 * @ throws NullPointerException if { @ code comparator } or any of { @ code elements } is null */
public static < E > ImmutableSortedSet < E > copyOf ( Comparator < ? super E > comparator , Iterator < ? extends E > elements ) { } }

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


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by the given { @ code
 * Comparator } . When multiple elements are equivalent according to { @ code compare ( ) } , only the
 * first one specified is included . 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 */
public static < E > ImmutableSortedSet < E > copyOf ( Comparator < ? super E > comparator , Iterable < ? extends E > elements ) { } }

implementation:
checkNotNull ( comparator ) ; boolean hasSameComparator = SortedIterables . hasSameComparator ( comparator , elements ) ; if ( hasSameComparator && ( elements instanceof ImmutableSortedSet ) ) { @ SuppressWarnings ( "unchecked" ) ImmutableSortedSet < E > original = ( ImmutableSortedSet < E > ) elements ; if ( ! original . isPartialView ( ) ) { return original ; } } @ SuppressWarnings ( "unchecked" ) // elements only contains E ' s ; it ' s safe .
E [ ] array = ( E [ ] ) Iterables . toArray ( elements ) ; return construct ( comparator , array . length , array ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the given elements sorted by the given { @ code
 * Comparator } . When multiple elements are equivalent according to { @ code compareTo ( ) } , only the
 * first one specified is included .
 * < 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 elements } is a synchronized or concurrent
 * collection that is currently being modified by another thread .
 * @ throws NullPointerException if { @ code comparator } or any of { @ code elements } is null
 * @ since 7.0 ( source - compatible since 2.0) */
public static < E > ImmutableSortedSet < E > copyOf ( Comparator < ? super E > comparator , Collection < ? extends E > elements ) { } }

implementation: return copyOf ( comparator , ( Iterable < ? extends E > ) elements ) ;


signature:
public class ImmutableSortedSet { /** * Returns an immutable sorted set containing the elements of a sorted set , 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 sortedSet } is a synchronized or concurrent
 * collection that is currently being modified by another thread .
 * @ throws NullPointerException if { @ code sortedSet } or any of its elements is null */
public static < E > ImmutableSortedSet < E > copyOfSorted ( SortedSet < E > sortedSet ) { } }

implementation: Comparator < ? super E > comparator = SortedIterables . comparator ( sortedSet ) ; ImmutableList < E > list = ImmutableList . copyOf ( sortedSet ) ; if ( list . isEmpty ( ) ) { return emptySet ( comparator ) ; } else { return new RegularImmutableSortedSet < E > ( list , comparator ) ; }


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

implementation: Comparator < ? super K > comparator = comparator ( ) ; if ( comparator == null ) { return ( ( Comparable < Object > ) k1 ) . compareTo ( k2 ) ; } else { return ( ( Comparator < Object > ) comparator ) . compare ( k1 , k2 ) ; }


signature:
public class ForwardingSortedMap { /** * A sensible default implementation of { @ link # subMap ( Object , Object ) } in terms of { @ link
 * # headMap ( Object ) } and { @ link # tailMap ( Object ) } . In some situations , you may wish to override
 * { @ link # subMap ( Object , Object ) } to forward to this implementation .
 * @ since 7.0 */
@ Beta protected SortedMap < K , V > standardSubMap ( K fromKey , K toKey ) { } }

implementation: checkArgument ( unsafeCompare ( fromKey , toKey ) <= 0 , "fromKey must be <= toKey" ) ; return tailMap ( fromKey ) . headMap ( toKey ) ;


signature:
public class ValueGraphBuilder { /** * Returns a { @ link ValueGraphBuilder } initialized with all properties queryable from { @ code
 * graph } .
 * < p > The " queryable " properties are those that are exposed through the { @ link ValueGraph }
 * interface , such as { @ link ValueGraph # isDirected ( ) } . Other properties , such as { @ link
 * # expectedNodeCount ( int ) } , are not set in the new builder . */
public static < N , V > ValueGraphBuilder < N , V > from ( ValueGraph < N , V > graph ) { } }

implementation: return new ValueGraphBuilder < N , V > ( graph . isDirected ( ) ) . allowsSelfLoops ( graph . allowsSelfLoops ( ) ) . nodeOrder ( graph . nodeOrder ( ) ) ;


signature:
public class ValueGraphBuilder { /** * Returns an { @ link ImmutableValueGraph # Builder } with the properties of this { @ link
 * ValueGraphBuilder } .
 * < p > The returned builder can be used for populating an { @ link ImmutableValueGraph } .
 * @ since NEXT */
public < N1 extends N , V1 extends V > ImmutableValueGraph . Builder < N1 , V1 > immutable ( ) { } }

implementation: ValueGraphBuilder < N1 , V1 > castBuilder = cast ( ) ; return new ImmutableValueGraph . Builder < > ( castBuilder ) ;


signature:
public class ValueGraphBuilder { /** * Specifies the expected number of nodes in the graph .
 * @ throws IllegalArgumentException if { @ code expectedNodeCount } is negative */
public ValueGraphBuilder < N , V > expectedNodeCount ( int expectedNodeCount ) { } }

implementation: this . expectedNodeCount = Optional . of ( checkNonNegative ( expectedNodeCount ) ) ; return this ;


signature:
public class ValueGraphBuilder { /** * Specifies the order of iteration for the elements of { @ link Graph # nodes ( ) } . */
public < N1 extends N > ValueGraphBuilder < N1 , V > nodeOrder ( ElementOrder < N1 > nodeOrder ) { } }

implementation: ValueGraphBuilder < N1 , V > newBuilder = cast ( ) ; newBuilder . nodeOrder = checkNotNull ( nodeOrder ) ; return newBuilder ;


signature:
public class Floats { /** * Returns the start position of the first occurrence of the specified { @ code target } within
 * { @ code array } , or { @ code - 1 } if there is no such occurrence .
 * < p > More formally , returns the lowest index { @ code i } such that { @ code Arrays . copyOfRange ( array ,
 * i , i + target . length ) } contains exactly the same elements as { @ code target } .
 * < p > Note that this always returns { @ code - 1 } when { @ code target } contains { @ code NaN } .
 * @ param array the array to search for the sequence { @ code target }
 * @ param target the array to search for as a sub - sequence of { @ code array } */
public static int indexOf ( float [ ] array , float [ ] target ) { } }

implementation: checkNotNull ( array , "array" ) ; checkNotNull ( target , "target" ) ; if ( target . length == 0 ) { return 0 ; } outer : for ( int i = 0 ; i < array . length - target . length + 1 ; i ++ ) { for ( int j = 0 ; j < target . length ; j ++ ) { if ( array [ i + j ] != target [ j ] ) { continue outer ; } } return i ; } return - 1 ;


signature:
public class Floats { /** * TODO ( kevinb ) : consider making this public */
private static int lastIndexOf ( float [ ] array , float target , int start , int end ) { } }

implementation: for ( int i = end - 1 ; i >= start ; i -- ) { if ( array [ i ] == target ) { return i ; } } return - 1 ;


signature:
public class Floats { /** * Returns the value nearest to { @ code value } which is within the closed range { @ code [ min . . max ] } .
 * < p > If { @ code value } is within the range { @ code [ min . . max ] } , { @ code value } is returned
 * unchanged . If { @ code value } is less than { @ code min } , { @ code min } is returned , and if { @ code
 * value } is greater than { @ code max } , { @ code max } is returned .
 * @ param value the { @ code float } value to constrain
 * @ param min the lower bound ( inclusive ) of the range to constrain { @ code value } to
 * @ param max the upper bound ( inclusive ) of the range to constrain { @ code value } to
 * @ throws IllegalArgumentException if { @ code min > max }
 * @ since 21.0 */
@ Beta public static float constrainToRange ( float value , float min , float max ) { } }

implementation: checkArgument ( min <= max , "min (%s) must be less than or equal to max (%s)" , min , max ) ; return Math . min ( Math . max ( value , min ) , max ) ;


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

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


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

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


signature:
public class Floats { /** * Parses the specified string as a single - precision floating point value . The ASCII character
 * { @ code ' - ' } ( < code > ' & # 92 ; u002D ' < / code > ) is recognized as the minus sign .
 * < p > Unlike { @ link Float # parseFloat ( String ) } , this method returns { @ code null } instead of
 * throwing an exception if parsing fails . Valid inputs are exactly those accepted by { @ link
 * Float # valueOf ( String ) } , except that leading and trailing whitespace is not permitted .
 * < p > This implementation is likely to be faster than { @ code Float . parseFloat } if many failures
 * are expected .
 * @ param string the string representation of a { @ code float } value
 * @ return the floating point value represented by { @ code string } , or { @ code null } if { @ code
 * string } has a length of zero or cannot be parsed as a { @ code float } value
 * @ since 14.0 */
@ Beta @ GwtIncompatible // regular expressions
@ NullableDecl public static Float tryParse ( String string ) { } }

implementation:
if ( Doubles . FLOATING_POINT_PATTERN . matcher ( string ) . matches ( ) ) { // TODO ( lowasser ) : could be potentially optimized , but only with
// extensive testing
try { return Float . parseFloat ( string ) ; } catch ( NumberFormatException e ) { // Float . parseFloat has changed specs several times , so fall through
// gracefully
} } return null ;


signature:
public class EnumHashBiMap { /** * Constructs a new bimap with the same mappings as the specified map . If the specified map is an
 * { @ code EnumHashBiMap } or an { @ link EnumBiMap } , the new bimap has the same key type as the input
 * bimap . Otherwise , the specified map must contain at least one mapping , in order to determine
 * the key type .
 * @ param map the map whose mappings are to be placed in this map
 * @ throws IllegalArgumentException if map is not an { @ code EnumBiMap } or an { @ code EnumHashBiMap }
 * instance and contains no mappings */
public static < K extends Enum < K > , V > EnumHashBiMap < K , V > create ( Map < K , ? extends V > map ) { } }

implementation: EnumHashBiMap < K , V > bimap = create ( EnumBiMap . inferKeyType ( map ) ) ; bimap . putAll ( map ) ; return bimap ;


signature:
public class Comparators { /** * think tip it over into being worthwhile . */
public static < T , S extends T > Comparator < Iterable < S > > lexicographical ( Comparator < T > comparator ) { } }

implementation: return new LexicographicalOrdering < S > ( checkNotNull ( comparator ) ) ;


signature:
public class ArrayBasedCharEscaper { /** * This is overridden to improve performance . Rough benchmarking shows that this almost doubles
 * the speed when processing strings that do not require any escaping . */
@ Override public final String escape ( String s ) { } }

implementation:
checkNotNull ( s ) ; // GWT specific check ( do not optimize ) .
for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( ( c < replacementsLength && replacements [ c ] != null ) || c > safeMax || c < safeMin ) { return escapeSlow ( s , i ) ; } } return s ;


signature:
public class ArrayBasedCharEscaper { /** * Escapes a single character using the replacement array and safe range values . If the given
 * character does not have an explicit replacement and lies outside the safe range then { @ link
 * # escapeUnsafe } is called . */
@ Override protected final char [ ] escape ( char c ) { } }

implementation: if ( c < replacementsLength ) { char [ ] chars = replacements [ c ] ; if ( chars != null ) { return chars ; } } if ( c >= safeMin && c <= safeMax ) { return null ; } return escapeUnsafe ( c ) ;


signature:
public class Finalizer { /** * Starts the Finalizer thread . FinalizableReferenceQueue calls this method reflectively .
 * @ param finalizableReferenceClass FinalizableReference . class .
 * @ param queue a reference queue that the thread will poll .
 * @ param frqReference a phantom reference to the FinalizableReferenceQueue , which will be queued
 * either when the FinalizableReferenceQueue is no longer referenced anywhere , or when its
 * close ( ) method is called . */
public static void startFinalizer ( Class < ? > finalizableReferenceClass , ReferenceQueue < Object > queue , PhantomReference < Object > frqReference ) { } }

implementation:
/* * We use FinalizableReference . class for two things :
 * 1 ) To invoke FinalizableReference . finalizeReferent ( )
 * 2 ) To detect when FinalizableReference ' s class loader has to be garbage collected , at which
 * point , Finalizer can stop running */
if ( ! finalizableReferenceClass . getName ( ) . equals ( FINALIZABLE_REFERENCE ) ) { throw new IllegalArgumentException ( "Expected " + FINALIZABLE_REFERENCE + "." ) ; } Finalizer finalizer = new Finalizer ( finalizableReferenceClass , queue , frqReference ) ; String threadName = Finalizer . class . getName ( ) ; Thread thread = null ; if ( bigThreadConstructor != null ) { try { boolean inheritThreadLocals = false ; long defaultStackSize = 0 ; thread = bigThreadConstructor . newInstance ( ( ThreadGroup ) null , finalizer , threadName , defaultStackSize , inheritThreadLocals ) ; } catch ( Throwable t ) { logger . log ( Level . INFO , "Failed to create a thread without inherited thread-local values" , t ) ; } } if ( thread == null ) { thread = new Thread ( ( ThreadGroup ) null , finalizer , threadName ) ; } thread . setDaemon ( true ) ; try { if ( inheritableThreadLocals != null ) { inheritableThreadLocals . set ( thread , null ) ; } } catch ( Throwable t ) { logger . log ( Level . INFO , "Failed to clear thread local values inherited by reference finalizer thread." , t ) ; } thread . start ( ) ;


signature:
public class Finalizer { /** * Looks up FinalizableReference . finalizeReferent ( ) method . */
@ NullableDecl private Method getFinalizeReferentMethod ( ) { } }

implementation:
Class < ? > finalizableReferenceClass = finalizableReferenceClassReference . get ( ) ; if ( finalizableReferenceClass == null ) { /* * FinalizableReference ' s class loader was reclaimed . While there ' s a chance that other
 * finalizable references could be enqueued subsequently ( at which point the class loader
 * would be resurrected by virtue of us having a strong reference to it ) , we should pretty
 * much just shut down and make sure we don ' t keep it alive any longer than necessary . */
return null ; } try { return finalizableReferenceClass . getMethod ( "finalizeReferent" ) ; } catch ( NoSuchMethodException e ) { throw new AssertionError ( e ) ; }


signature:
public class AbstractScheduledService { /** * Returns the { @ link ScheduledExecutorService } that will be used to execute the { @ link # startUp } ,
 * { @ link # runOneIteration } and { @ link # shutDown } methods . If this method is overridden the
 * executor will not be { @ linkplain ScheduledExecutorService # shutdown shutdown } when this service
 * { @ linkplain Service . State # TERMINATED terminates } or { @ linkplain Service . State # TERMINATED
 * fails } . Subclasses may override this method to supply a custom { @ link ScheduledExecutorService }
 * instance . This method is guaranteed to only be called once .
 * < p > By default this returns a new { @ link ScheduledExecutorService } with a single thread thread
 * pool that sets the name of the thread to the { @ linkplain # serviceName ( ) service name } . Also ,
 * the pool will be { @ linkplain ScheduledExecutorService # shutdown ( ) shut down } when the service
 * { @ linkplain Service . State # TERMINATED terminates } or { @ linkplain Service . State # TERMINATED
 * fails } . */
protected ScheduledExecutorService executor ( ) { } }

implementation:
@ WeakOuter class ThreadFactoryImpl implements ThreadFactory { @ Override public Thread newThread ( Runnable runnable ) { return MoreExecutors . newThread ( serviceName ( ) , runnable ) ; } } final ScheduledExecutorService executor = Executors . newSingleThreadScheduledExecutor ( new ThreadFactoryImpl ( ) ) ; // Add a listener to shutdown the executor after the service is stopped . This ensures that the
// JVM shutdown will not be prevented from exiting after this service has stopped or failed .
// Technically this listener is added after start ( ) was called so it is a little gross , but it
// is called within doStart ( ) so we know that the service cannot terminate or fail concurrently
// with adding this listener so it is impossible to miss an event that we are interested in .
addListener ( new Listener ( ) { @ Override public void terminated ( State from ) { executor . shutdown ( ) ; } @ Override public void failed ( State from , Throwable failure ) { executor . shutdown ( ) ; } } , directExecutor ( ) ) ; return executor ;


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

implementation: return ( graph instanceof ImmutableValueGraph ) ? ( ImmutableValueGraph < N , V > ) graph : new ImmutableValueGraph < N , V > ( graph ) ;


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

implementation: return checkNotNull ( graph ) ;


signature:
public class AbstractListMultimap { /** * { @ inheritDoc }
 * < p > Because the values for a given key may have duplicates and follow the insertion ordering ,
 * this method returns a { @ link List } , instead of the { @ link Collection } specified in the { @ link
 * Multimap } interface . */
@ CanIgnoreReturnValue @ Override public List < V > removeAll ( @ NullableDecl Object key ) { } }

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


signature:
public class ImmutableSortedSetFauxverideShim { /** * Not supported . < b > You are attempting to create a set that may contain a non - { @ code Comparable }
 * element . < / b > Proper calls will resolve to the version in { @ code ImmutableSortedSet } , not this
 * dummy version .
 * @ throws UnsupportedOperationException always
 * @ deprecated < b > Pass the parameters of type { @ code Comparable } to use { @ link
 * ImmutableSortedSet # of ( Comparable , Comparable ) } . < / b > */
@ Deprecated public static < E > ImmutableSortedSet < E > of ( E e1 , E e2 ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class ImmutableSortedMap { /** * Returns the empty sorted map . */
@ SuppressWarnings ( "unchecked" ) // unsafe , comparator ( ) returns a comparator on the specified type
// TODO ( kevinb ) : evaluate whether or not of ( ) . comparator ( ) should return null
public static < K , V > ImmutableSortedMap < K , V > of ( ) { } }

implementation: return ( ImmutableSortedMap < K , V > ) NATURAL_EMPTY_MAP ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing a single entry . */
public static < K extends Comparable < ? super K > , V > ImmutableSortedMap < K , V > of ( K k1 , V v1 ) { } }

implementation: return of ( Ordering . natural ( ) , k1 , v1 ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable sorted map containing the given entries , sorted by the natural ordering of
 * their keys .
 * @ throws IllegalArgumentException if the two keys are equal according to their natural ordering */
@ SuppressWarnings ( "unchecked" ) public static < K extends Comparable < ? super K > , V > ImmutableSortedMap < K , V > of ( K k1 , V v1 , K k2 , V v2 ) { } }

implementation: return ofEntries ( entryOf ( k1 , v1 ) , entryOf ( k2 , v2 ) ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing the same entries as { @ code map } , sorted by the natural
 * ordering of the keys .
 * < 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 a map with keys that are not mutually
 * comparable .
 * @ throws ClassCastException if the keys in { @ code map } are not mutually comparable
 * @ throws NullPointerException if any key or value in { @ code map } is null
 * @ throws IllegalArgumentException if any two keys are equal according to their natural ordering */
public static < K , V > ImmutableSortedMap < K , V > copyOf ( Map < ? extends K , ? extends V > map ) { } }

implementation:
// Hack around K not being a subtype of Comparable .
// Unsafe , see ImmutableSortedSetFauxverideShim .
@ SuppressWarnings ( "unchecked" ) Ordering < K > naturalOrder = ( Ordering < K > ) NATURAL_ORDER ; return copyOfInternal ( map , naturalOrder ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing the same entries as { @ code map } , with keys sorted by the
 * provided comparator .
 * < p > Despite the method name , this method attempts to avoid actually copying the data when it is
 * safe to do so . The exact circumstances under which a copy will or will not be performed are
 * undocumented and subject to change .
 * @ throws NullPointerException if any key or value in { @ code map } is null
 * @ throws IllegalArgumentException if any two keys are equal according to the comparator */
public static < K , V > ImmutableSortedMap < K , V > copyOf ( Map < ? extends K , ? extends V > map , Comparator < ? super K > comparator ) { } }

implementation: return copyOfInternal ( map , checkNotNull ( comparator ) ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing the given entries , with keys sorted by the provided
 * comparator .
 * < p > This method is not type - safe , as it may be called on a map with keys that are not mutually
 * comparable .
 * @ throws NullPointerException if any key or value in { @ code map } is null
 * @ throws IllegalArgumentException if any two keys are equal according to the comparator
 * @ since 19.0 */
@ Beta public static < K , V > ImmutableSortedMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { } }

implementation:
// Hack around K not being a subtype of Comparable .
// Unsafe , see ImmutableSortedSetFauxverideShim .
@ SuppressWarnings ( "unchecked" ) Ordering < K > naturalOrder = ( Ordering < K > ) NATURAL_ORDER ; return copyOf ( entries , naturalOrder ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing the given entries , with keys sorted by the provided
 * comparator .
 * @ throws NullPointerException if any key or value in { @ code map } is null
 * @ throws IllegalArgumentException if any two keys are equal according to the comparator
 * @ since 19.0 */
@ Beta public static < K , V > ImmutableSortedMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries , Comparator < ? super K > comparator ) { } }

implementation: return fromEntries ( checkNotNull ( comparator ) , false , entries ) ;


signature:
public class ImmutableSortedMap { /** * Returns an immutable map containing the same entries as the provided sorted map , with the same
 * ordering .
 * < p > Despite the method name , this method attempts to avoid actually copying the data when it is
 * safe to do so . The exact circumstances under which a copy will or will not be performed are
 * undocumented and subject to change .
 * @ throws NullPointerException if any key or value in { @ code map } is null */
@ SuppressWarnings ( "unchecked" ) public static < K , V > ImmutableSortedMap < K , V > copyOfSorted ( SortedMap < K , ? extends V > map ) { } }

implementation:
Comparator < ? super K > comparator = map . comparator ( ) ; if ( comparator == null ) { // If map has a null comparator , the keys should have a natural ordering ,
// even though K doesn ' t explicitly implement Comparable .
comparator = ( Comparator < ? super K > ) NATURAL_ORDER ; } if ( map instanceof ImmutableSortedMap ) { // TODO ( kevinb ) : Prove that this cast is safe , even though
// Collections . unmodifiableSortedMap requires the same key type .
@ SuppressWarnings ( "unchecked" ) ImmutableSortedMap < K , V > kvMap = ( ImmutableSortedMap < K , V > ) map ; if ( ! kvMap . isPartialView ( ) ) { return kvMap ; } } return fromEntries ( comparator , true , map . entrySet ( ) ) ;


signature:
public class ImmutableSortedMap { /** * Accepts a collection of possibly - null entries . If { @ code sameComparator } , then it is assumed
 * that they do not need to be sorted or checked for dupes . */
private static < K , V > ImmutableSortedMap < K , V > fromEntries ( Comparator < ? super K > comparator , boolean sameComparator , Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { } }

implementation:
// " adding " type params to an array of a raw type should be safe as
// long as no one can ever cast that same array instance back to a
// raw type .
@ SuppressWarnings ( "unchecked" ) Entry < K , V > [ ] entryArray = ( Entry [ ] ) Iterables . toArray ( entries , EMPTY_ENTRY_ARRAY ) ; return fromEntries ( comparator , sameComparator , entryArray , entryArray . length ) ;


signature:
public class ImmutableSortedMap { /** * Returns a builder that creates immutable sorted maps whose keys are ordered by their natural
 * ordering . The sorted maps use { @ link Ordering # natural ( ) } as the comparator . */
public static < K extends Comparable < ? > , V > Builder < K , V > naturalOrder ( ) { } }

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


signature:
public class ImmutableSortedMap { /** * Returns a builder that creates immutable sorted maps with an explicit comparator . If the
 * comparator has a more general type than the map ' s keys , such as creating a { @ code
 * SortedMap < Integer , String > } with a { @ code Comparator < Number > } , use the { @ link Builder }
 * constructor instead .
 * @ throws NullPointerException if { @ code comparator } is null */
public static < K , V > Builder < K , V > orderedBy ( Comparator < K > comparator ) { } }

implementation: return new Builder < > ( comparator ) ;


signature:
public class ImmutableSortedMap { /** * This method returns a { @ code ImmutableSortedMap } , consisting of the entries whose keys are less
 * than { @ code toKey } .
 * < p > The { @ link SortedMap # headMap } documentation states that a submap of a submap throws an
 * { @ link IllegalArgumentException } if passed a { @ code toKey } greater than an earlier { @ code
 * toKey } . However , this method doesn ' t throw an exception in that situation , but instead keeps
 * the original { @ code toKey } . */
@ Override public ImmutableSortedMap < K , V > headMap ( K toKey ) { } }

implementation: return headMap ( toKey , false ) ;


signature:
public class ImmutableSortedMap { /** * This method returns a { @ code ImmutableSortedMap } , consisting of the entries whose keys are less
 * than ( or equal to , if { @ code inclusive } ) { @ code toKey } .
 * < p > The { @ link SortedMap # headMap } documentation states that a submap of a submap throws an
 * { @ link IllegalArgumentException } if passed a { @ code toKey } greater than an earlier { @ code
 * toKey } . However , this method doesn ' t throw an exception in that situation , but instead keeps
 * the original { @ code toKey } .
 * @ since 12.0 */
@ Override public ImmutableSortedMap < K , V > headMap ( K toKey , boolean inclusive ) { } }

implementation: return getSubMap ( 0 , keySet . headIndex ( checkNotNull ( toKey ) , inclusive ) ) ;


signature:
public class ImmutableSortedMap { /** * This method returns a { @ code ImmutableSortedMap } , consisting of the entries whose keys ranges
 * from { @ code fromKey } to { @ code toKey } , inclusive or exclusive as indicated by the boolean
 * flags .
 * < p > The { @ link SortedMap # subMap } documentation states that a submap of a submap throws an { @ link
 * IllegalArgumentException } if passed a { @ code fromKey } less than an earlier { @ code fromKey } .
 * However , this method doesn ' t throw an exception in that situation , but instead keeps the
 * original { @ code fromKey } . Similarly , this method keeps the original { @ code toKey } , instead of
 * throwing an exception , if passed a { @ code toKey } greater than an earlier { @ code toKey } .
 * @ since 12.0 */
@ Override public ImmutableSortedMap < K , V > subMap ( K fromKey , boolean fromInclusive , K toKey , boolean toInclusive ) { } }

implementation: checkNotNull ( fromKey ) ; checkNotNull ( toKey ) ; checkArgument ( comparator ( ) . compare ( fromKey , toKey ) <= 0 , "expected fromKey <= toKey but %s > %s" , fromKey , toKey ) ; return headMap ( toKey , toInclusive ) . tailMap ( fromKey , fromInclusive ) ;


signature:
public class ImmutableSortedMap { /** * This method returns a { @ code ImmutableSortedMap } , consisting of the entries whose keys are
 * greater than or equals to { @ code fromKey } .
 * < p > The { @ link SortedMap # tailMap } documentation states that a submap of a submap throws an
 * { @ link IllegalArgumentException } if passed a { @ code fromKey } less than an earlier { @ code
 * fromKey } . However , this method doesn ' t throw an exception in that situation , but instead keeps
 * the original { @ code fromKey } . */
@ Override public ImmutableSortedMap < K , V > tailMap ( K fromKey ) { } }

implementation: return tailMap ( fromKey , true ) ;


signature:
public class ImmutableSortedMap { /** * This method returns a { @ code ImmutableSortedMap } , consisting of the entries whose keys are
 * greater than ( or equal to , if { @ code inclusive } ) { @ code fromKey } .
 * < p > The { @ link SortedMap # tailMap } documentation states that a submap of a submap throws an
 * { @ link IllegalArgumentException } if passed a { @ code fromKey } less than an earlier { @ code
 * fromKey } . However , this method doesn ' t throw an exception in that situation , but instead keeps
 * the original { @ code fromKey } .
 * @ since 12.0 */
@ Override public ImmutableSortedMap < K , V > tailMap ( K fromKey , boolean inclusive ) { } }

implementation: return getSubMap ( keySet . tailIndex ( checkNotNull ( fromKey ) , inclusive ) , size ( ) ) ;


signature:
public class FarmHashFingerprint64 { /** * Computes intermediate hash of 32 bytes of byte array from the given offset . Results are
 * returned in the output array because when we last measured , this was 12 % faster than allocating
 * new arrays every time . */
private static void weakHashLength32WithSeeds ( byte [ ] bytes , int offset , long seedA , long seedB , long [ ] output ) { } }

implementation: long part1 = load64 ( bytes , offset ) ; long part2 = load64 ( bytes , offset + 8 ) ; long part3 = load64 ( bytes , offset + 16 ) ; long part4 = load64 ( bytes , offset + 24 ) ; seedA += part1 ; seedB = rotateRight ( seedB + seedA + part4 , 21 ) ; long c = seedA ; seedA += part2 ; seedA += part3 ; seedB += rotateRight ( seedA , 44 ) ; output [ 0 ] = seedA + part4 ; output [ 1 ] = seedB + c ;


signature:
public class AbstractService { /** * Checks that the current state is equal to the expected state . */
@ GuardedBy ( "monitor" ) private void checkCurrentState ( State expected ) { } }

implementation:
State actual = state ( ) ; if ( actual != expected ) { if ( actual == FAILED ) { // Handle this specially so that we can include the failureCause , if there is one .
throw new IllegalStateException ( "Expected the service " + this + " to be " + expected + ", but the service has FAILED" , failureCause ( ) ) ; } throw new IllegalStateException ( "Expected the service " + this + " to be " + expected + ", but was " + actual ) ; }


signature:
public class AbstractService { /** * Implementing classes should invoke this method once their service has started . It will cause
 * the service to transition from { @ link State # STARTING } to { @ link State # RUNNING } .
 * @ throws IllegalStateException if the service is not { @ link State # STARTING } . */
protected final void notifyStarted ( ) { } }

implementation:
monitor . enter ( ) ; try { // We have to examine the internal state of the snapshot here to properly handle the stop
// while starting case .
if ( snapshot . state != STARTING ) { IllegalStateException failure = new IllegalStateException ( "Cannot notifyStarted() when the service is " + snapshot . state ) ; notifyFailed ( failure ) ; throw failure ; } if ( snapshot . shutdownWhenStartupFinishes ) { snapshot = new StateSnapshot ( STOPPING ) ; // We don ' t call listeners here because we already did that when we set the
// shutdownWhenStartupFinishes flag .
doStop ( ) ; } else { snapshot = new StateSnapshot ( RUNNING ) ; enqueueRunningEvent ( ) ; } } finally { monitor . leave ( ) ; dispatchListenerEvents ( ) ; }


signature:
public class AbstractService { /** * Implementing classes should invoke this method once their service has stopped . It will cause
 * the service to transition from { @ link State # STARTING } or { @ link State # STOPPING } to { @ link
 * State # TERMINATED } .
 * @ throws IllegalStateException if the service is not one of { @ link State # STOPPING } , { @ link
 * State # STARTING } , or { @ link State # RUNNING } . */
protected final void notifyStopped ( ) { } }

implementation: monitor . enter ( ) ; try { State previous = state ( ) ; switch ( previous ) { case NEW : case TERMINATED : case FAILED : throw new IllegalStateException ( "Cannot notifyStopped() when the service is " + previous ) ; case RUNNING : case STARTING : case STOPPING : snapshot = new StateSnapshot ( TERMINATED ) ; enqueueTerminatedEvent ( previous ) ; break ; } } finally { monitor . leave ( ) ; dispatchListenerEvents ( ) ; }


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 ; } } Object [ ] array = elements . toArray ( ) ; return construct ( 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 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 construct ( elements . length , elements . clone ( ) ) ; }


signature:
public class MoreFiles { /** * Returns a view of the given { @ code path } as a { @ link CharSource } using the given { @ code
 * charset } .
 * < p > Any { @ linkplain OpenOption open options } provided are used when opening streams to the file
 * and may affect the behavior of the returned source and the streams it provides . See { @ link
 * StandardOpenOption } for the standard options that may be provided . Providing no options is
 * equivalent to providing the { @ link StandardOpenOption # READ READ } option . */
public static CharSource asCharSource ( Path path , Charset charset , OpenOption ... options ) { } }

implementation: return asByteSource ( path , options ) . asCharSource ( charset ) ;


signature:
public class MoreFiles { /** * Returns a view of the given { @ code path } as a { @ link CharSink } using the given { @ code charset } .
 * < p > Any { @ linkplain OpenOption open options } provided are used when opening streams to the file
 * and may affect the behavior of the returned sink and the streams it provides . See { @ link
 * StandardOpenOption } for the standard options that may be provided . Providing no options is
 * equivalent to providing the { @ link StandardOpenOption # CREATE CREATE } , { @ link
 * StandardOpenOption # TRUNCATE _ EXISTING TRUNCATE _ EXISTING } and { @ link StandardOpenOption # WRITE
 * WRITE } options . */
public static CharSink asCharSink ( Path path , Charset charset , OpenOption ... options ) { } }

implementation: return asByteSink ( path , options ) . asCharSink ( charset ) ;


signature:
public class MoreFiles { /** * Returns an immutable list of paths to the files contained in the given directory .
 * @ throws NoSuchFileException if the file does not exist < i > ( optional specific exception ) < / i >
 * @ throws NotDirectoryException if the file could not be opened because it is not a directory
 * < i > ( optional specific exception ) < / i >
 * @ throws IOException if an I / O error occurs */
public static ImmutableList < Path > listFiles ( Path dir ) throws IOException { } }

implementation: try ( DirectoryStream < Path > stream = Files . newDirectoryStream ( dir ) ) { return ImmutableList . copyOf ( stream ) ; } catch ( DirectoryIteratorException e ) { throw e . getCause ( ) ; }


signature:
public class MoreFiles { /** * Returns a predicate that returns the result of { @ link java . nio . file . Files # isDirectory ( Path ,
 * LinkOption . . . ) } on input paths with the given link options . */
public static Predicate < Path > isDirectory ( LinkOption ... options ) { } }

implementation: final LinkOption [ ] optionsCopy = options . clone ( ) ; return new Predicate < Path > ( ) { @ Override public boolean apply ( Path input ) { return Files . isDirectory ( input , optionsCopy ) ; } @ Override public String toString ( ) { return "MoreFiles.isDirectory(" + Arrays . toString ( optionsCopy ) + ")" ; } } ;


signature:
public class MoreFiles { /** * Returns whether or not the file with the given name in the given dir is a directory . */
private static boolean isDirectory ( SecureDirectoryStream < Path > dir , Path name , LinkOption ... options ) throws IOException { } }

implementation: return dir . getFileAttributeView ( name , BasicFileAttributeView . class , options ) . readAttributes ( ) . isDirectory ( ) ;


signature:
public class MoreFiles { /** * Returns true if the files located by the given paths exist , are not directories , and contain
 * the same bytes .
 * @ throws IOException if an I / O error occurs
 * @ since 22.0 */
public static boolean equal ( Path path1 , Path path2 ) throws IOException { } }

implementation:
checkNotNull ( path1 ) ; checkNotNull ( path2 ) ; if ( Files . isSameFile ( path1 , path2 ) ) { return true ; } /* * Some operating systems may return zero as the length for files denoting system - dependent
 * entities such as devices or pipes , in which case we must fall back on comparing the bytes
 * directly . */
ByteSource source1 = asByteSource ( path1 ) ; ByteSource source2 = asByteSource ( path2 ) ; long len1 = source1 . sizeIfKnown ( ) . or ( 0L ) ; long len2 = source2 . sizeIfKnown ( ) . or ( 0L ) ; if ( len1 != 0 && len2 != 0 && len1 != len2 ) { return false ; } return source1 . contentEquals ( source2 ) ;


signature:
public class MoreFiles { /** * Like the unix command of the same name , creates an empty file or updates the last modified
 * timestamp of the existing file at the given path to the current system time . */
@ SuppressWarnings ( "GoodTime" ) // reading system time without TimeSource
public static void touch ( Path path ) throws IOException { } }

implementation:
checkNotNull ( path ) ; try { Files . setLastModifiedTime ( path , FileTime . fromMillis ( System . currentTimeMillis ( ) ) ) ; } catch ( NoSuchFileException e ) { try { Files . createFile ( path ) ; } catch ( FileAlreadyExistsException ignore ) { // The file didn ' t exist when we called setLastModifiedTime , but it did when we called
// createFile , so something else created the file in between . The end result is
// what we wanted : a new file that probably has its last modified time set to approximately
// now . Or it could have an arbitrary last modified time set by the creator , but that ' s no
// different than if another process set its last modified time to something else after we
// created it here .
} }


signature:
public class MoreFiles { /** * Creates any necessary but nonexistent parent directories of the specified path . Note that if
 * this operation fails , it may have succeeded in creating some ( but not all ) of the necessary
 * parent directories . The parent directory is created with the given { @ code attrs } .
 * @ throws IOException if an I / O error occurs , or if any necessary but nonexistent parent
 * directories of the specified file could not be created . */
public static void createParentDirectories ( Path path , FileAttribute < ? > ... attrs ) throws IOException { } }

implementation:
// Interestingly , unlike File . getCanonicalFile ( ) , Path / Files provides no way of getting the
// canonical ( absolute , normalized , symlinks resolved , etc . ) form of a path to a nonexistent
// file . getCanonicalFile ( ) can at least get the canonical form of the part of the path which
// actually exists and then append the normalized remainder of the path to that .
Path normalizedAbsolutePath = path . toAbsolutePath ( ) . normalize ( ) ; Path parent = normalizedAbsolutePath . getParent ( ) ; if ( parent == null ) { // The given directory is a filesystem root . All zero of its ancestors exist . This doesn ' t
// mean that the root itself exists - - consider x : \ on a Windows machine without such a
// drive - - or even that the caller can create it , but this method makes no such guarantees
// even for non - root files .
return ; } // Check if the parent is a directory first because createDirectories will fail if the parent
// exists and is a symlink to a directory . . . we ' d like for this to succeed in that case .
// ( I ' m kind of surprised that createDirectories would fail in that case ; doesn ' t seem like
// what you ' d want to happen . )
if ( ! Files . isDirectory ( parent ) ) { Files . createDirectories ( parent , attrs ) ; if ( ! Files . isDirectory ( parent ) ) { throw new IOException ( "Unable to create parent directories of " + path ) ; } }


signature:
public class MoreFiles { /** * Returns the < a href = " http : / / en . wikipedia . org / wiki / Filename _ extension " > file extension < / a > for
 * the file at the given path , or the empty string if the file has no extension . The result does
 * not include the ' { @ code . } ' .
 * < p > < b > Note : < / b > This method simply returns everything after the last ' { @ code . } ' in the file ' s
 * name as determined by { @ link Path # getFileName } . It does not account for any filesystem - specific
 * behavior that the { @ link Path } API does not already account for . For example , on NTFS it will
 * report { @ code " txt " } as the extension for the filename { @ code " foo . exe : . txt " } even though NTFS
 * will drop the { @ code " : . txt " } part of the name when the file is actually created on the
 * filesystem due to NTFS ' s < a href = " https : / / goo . gl / vTpJi4 " > Alternate Data Streams < / a > . */
public static String getFileExtension ( Path path ) { } }

implementation:
Path name = path . getFileName ( ) ; // null for empty paths and root - only paths
if ( name == null ) { return "" ; } String fileName = name . toString ( ) ; int dotIndex = fileName . lastIndexOf ( '.' ) ; return dotIndex == - 1 ? "" : fileName . substring ( dotIndex + 1 ) ;


signature:
public class MoreFiles { /** * Deletes the file or directory at the given { @ code path } recursively . Deletes symbolic links ,
 * not their targets ( subject to the caveat below ) .
 * < p > If an I / O exception occurs attempting to read , open or delete any file under the given
 * directory , this method skips that file and continues . All such exceptions are collected and ,
 * after attempting to delete all files , an { @ code IOException } is thrown containing those
 * exceptions as { @ linkplain Throwable # getSuppressed ( ) suppressed exceptions } .
 * < h2 > Warning : Security of recursive deletes < / h2 >
 * < p > On a file system that supports symbolic links and does < i > not < / i > support { @ link
 * SecureDirectoryStream } , it is possible for a recursive delete to delete files and directories
 * that are < i > outside < / i > the directory being deleted . This can happen if , after checking that a
 * file is a directory ( and not a symbolic link ) , that directory is replaced by a symbolic link to
 * an outside directory before the call that opens the directory to read its entries .
 * < p > By default , this method throws { @ link InsecureRecursiveDeleteException } if it can ' t
 * guarantee the security of recursive deletes . If you wish to allow the recursive deletes anyway ,
 * pass { @ link RecursiveDeleteOption # ALLOW _ INSECURE } to this method to override that behavior .
 * @ throws NoSuchFileException if { @ code path } does not exist < i > ( optional specific exception ) < / i >
 * @ throws InsecureRecursiveDeleteException if the security of recursive deletes can ' t be
 * guaranteed for the file system and { @ link RecursiveDeleteOption # ALLOW _ INSECURE } was not
 * specified
 * @ throws IOException if { @ code path } or any file in the subtree rooted at it can ' t be deleted
 * for any reason */
public static void deleteRecursively ( Path path , RecursiveDeleteOption ... options ) throws IOException { } }

implementation:
Path parentPath = getParentPath ( path ) ; if ( parentPath == null ) { throw new FileSystemException ( path . toString ( ) , null , "can't delete recursively" ) ; } Collection < IOException > exceptions = null ; // created lazily if needed
try { boolean sdsSupported = false ; try ( DirectoryStream < Path > parent = Files . newDirectoryStream ( parentPath ) ) { if ( parent instanceof SecureDirectoryStream ) { sdsSupported = true ; exceptions = deleteRecursivelySecure ( ( SecureDirectoryStream < Path > ) parent , path . getFileName ( ) ) ; } } if ( ! sdsSupported ) { checkAllowsInsecure ( path , options ) ; exceptions = deleteRecursivelyInsecure ( path ) ; } } catch ( IOException e ) { if ( exceptions == null ) { throw e ; } else { exceptions . add ( e ) ; } } if ( exceptions != null ) { throwDeleteFailed ( path , exceptions ) ; }


signature:
public class MoreFiles { /** * Deletes all files within the directory at the given { @ code path } { @ linkplain # deleteRecursively
 * recursively } . Does not delete the directory itself . Deletes symbolic links , not their targets
 * ( subject to the caveat below ) . If { @ code path } itself is a symbolic link to a directory , that
 * link is followed and the contents of the directory it targets are deleted .
 * < p > If an I / O exception occurs attempting to read , open or delete any file under the given
 * directory , this method skips that file and continues . All such exceptions are collected and ,
 * after attempting to delete all files , an { @ code IOException } is thrown containing those
 * exceptions as { @ linkplain Throwable # getSuppressed ( ) suppressed exceptions } .
 * < h2 > Warning : Security of recursive deletes < / h2 >
 * < p > On a file system that supports symbolic links and does < i > not < / i > support { @ link
 * SecureDirectoryStream } , it is possible for a recursive delete to delete files and directories
 * that are < i > outside < / i > the directory being deleted . This can happen if , after checking that a
 * file is a directory ( and not a symbolic link ) , that directory is replaced by a symbolic link to
 * an outside directory before the call that opens the directory to read its entries .
 * < p > By default , this method throws { @ link InsecureRecursiveDeleteException } if it can ' t
 * guarantee the security of recursive deletes . If you wish to allow the recursive deletes anyway ,
 * pass { @ link RecursiveDeleteOption # ALLOW _ INSECURE } to this method to override that behavior .
 * @ throws NoSuchFileException if { @ code path } does not exist < i > ( optional specific exception ) < / i >
 * @ throws NotDirectoryException if the file at { @ code path } is not a directory < i > ( optional
 * specific exception ) < / i >
 * @ throws InsecureRecursiveDeleteException if the security of recursive deletes can ' t be
 * guaranteed for the file system and { @ link RecursiveDeleteOption # ALLOW _ INSECURE } was not
 * specified
 * @ throws IOException if one or more files can ' t be deleted for any reason */
public static void deleteDirectoryContents ( Path path , RecursiveDeleteOption ... options ) throws IOException { } }

implementation:
Collection < IOException > exceptions = null ; // created lazily if needed
try ( DirectoryStream < Path > stream = Files . newDirectoryStream ( path ) ) { if ( stream instanceof SecureDirectoryStream ) { SecureDirectoryStream < Path > sds = ( SecureDirectoryStream < Path > ) stream ; exceptions = deleteDirectoryContentsSecure ( sds ) ; } else { checkAllowsInsecure ( path , options ) ; exceptions = deleteDirectoryContentsInsecure ( stream ) ; } } catch ( IOException e ) { if ( exceptions == null ) { throw e ; } else { exceptions . add ( e ) ; } } if ( exceptions != null ) { throwDeleteFailed ( path , exceptions ) ; }


signature:
public class MoreFiles { /** * Secure recursive delete using { @ code SecureDirectoryStream } . Returns a collection of exceptions
 * that occurred or null if no exceptions were thrown . */
private static @ Nullable Collection < IOException > deleteRecursivelySecure ( SecureDirectoryStream < Path > dir , Path path ) { } }

implementation:
Collection < IOException > exceptions = null ; try { if ( isDirectory ( dir , path , NOFOLLOW_LINKS ) ) { try ( SecureDirectoryStream < Path > childDir = dir . newDirectoryStream ( path , NOFOLLOW_LINKS ) ) { exceptions = deleteDirectoryContentsSecure ( childDir ) ; } // If exceptions is not null , something went wrong trying to delete the contents of the
// directory , so we shouldn ' t try to delete the directory as it will probably fail .
if ( exceptions == null ) { dir . deleteDirectory ( path ) ; } } else { dir . deleteFile ( path ) ; } return exceptions ; } catch ( IOException e ) { return addException ( exceptions , e ) ; }


signature:
public class MoreFiles { /** * Secure method for deleting the contents of a directory using { @ code SecureDirectoryStream } .
 * Returns a collection of exceptions that occurred or null if no exceptions were thrown . */
private static @ Nullable Collection < IOException > deleteDirectoryContentsSecure ( SecureDirectoryStream < Path > dir ) { } }

implementation: Collection < IOException > exceptions = null ; try { for ( Path path : dir ) { exceptions = concat ( exceptions , deleteRecursivelySecure ( dir , path . getFileName ( ) ) ) ; } return exceptions ; } catch ( DirectoryIteratorException e ) { return addException ( exceptions , e . getCause ( ) ) ; }


signature:
public class MoreFiles { /** * Insecure recursive delete for file systems that don ' t support { @ code SecureDirectoryStream } .
 * Returns a collection of exceptions that occurred or null if no exceptions were thrown . */
private static @ Nullable Collection < IOException > deleteRecursivelyInsecure ( Path path ) { } }

implementation:
Collection < IOException > exceptions = null ; try { if ( Files . isDirectory ( path , NOFOLLOW_LINKS ) ) { try ( DirectoryStream < Path > stream = Files . newDirectoryStream ( path ) ) { exceptions = deleteDirectoryContentsInsecure ( stream ) ; } } // If exceptions is not null , something went wrong trying to delete the contents of the
// directory , so we shouldn ' t try to delete the directory as it will probably fail .
if ( exceptions == null ) { Files . delete ( path ) ; } return exceptions ; } catch ( IOException e ) { return addException ( exceptions , e ) ; }


signature:
public class MoreFiles { /** * Simple , insecure method for deleting the contents of a directory for file systems that don ' t
 * support { @ code SecureDirectoryStream } . Returns a collection of exceptions that occurred or null
 * if no exceptions were thrown . */
private static @ Nullable Collection < IOException > deleteDirectoryContentsInsecure ( DirectoryStream < Path > dir ) { } }

implementation: Collection < IOException > exceptions = null ; try { for ( Path entry : dir ) { exceptions = concat ( exceptions , deleteRecursivelyInsecure ( entry ) ) ; } return exceptions ; } catch ( DirectoryIteratorException e ) { return addException ( exceptions , e . getCause ( ) ) ; }


signature:
public class MoreFiles { /** * Returns a path to the parent directory of the given path . If the path actually has a parent
 * path , this is simple . Otherwise , we need to do some trickier things . Returns null if the path
 * is a root or is the empty path . */
private static @ Nullable Path getParentPath ( Path path ) { } }

implementation:
Path parent = path . getParent ( ) ; // Paths that have a parent :
if ( parent != null ) { // " / foo " ( " / " )
// " foo / bar " ( " foo " )
// " C : \ foo " ( " C : \ " )
// " \ foo " ( " \ " - current drive for process on Windows )
// " C : foo " ( " C : " - working dir of drive C on Windows )
return parent ; } // Paths that don ' t have a parent :
if ( path . getNameCount ( ) == 0 ) { // " / " , " C : \ " , " \ " ( no parent )
// " " ( undefined , though typically parent of working dir )
// " C : " ( parent of working dir of drive C on Windows )
// For working dir paths ( " " and " C : " ) , return null because :
// A ) it ' s not specified that " " is the path to the working directory .
// B ) if we ' re getting this path for recursive delete , it ' s typically not possible to
// delete the working dir with a relative path anyway , so it ' s ok to fail .
// C ) if we ' re getting it for opening a new SecureDirectoryStream , there ' s no need to get
// the parent path anyway since we can safely open a DirectoryStream to the path without
// worrying about a symlink .
return null ; } else { // " foo " ( working dir )
return path . getFileSystem ( ) . getPath ( "." ) ; }


signature:
public class MoreFiles { /** * Checks that the given options allow an insecure delete , throwing an exception if not . */
private static void checkAllowsInsecure ( Path path , RecursiveDeleteOption [ ] options ) throws InsecureRecursiveDeleteException { } }

implementation: if ( ! Arrays . asList ( options ) . contains ( RecursiveDeleteOption . ALLOW_INSECURE ) ) { throw new InsecureRecursiveDeleteException ( path . toString ( ) ) ; }


signature:
public class MoreFiles { /** * Adds the given exception to the given collection , creating the collection if it ' s null . Returns
 * the collection . */
private static Collection < IOException > addException ( @ Nullable Collection < IOException > exceptions , IOException e ) { } }

implementation:
if ( exceptions == null ) { exceptions = new ArrayList < > ( ) ; // don ' t need Set semantics
} exceptions . add ( e ) ; return exceptions ;


signature:
public class MoreFiles { /** * Concatenates the contents of the two given collections of exceptions . If either collection is
 * null , the other collection is returned . Otherwise , the elements of { @ code other } are added to
 * { @ code exceptions } and { @ code exceptions } is returned . */
private static @ Nullable Collection < IOException > concat ( @ Nullable Collection < IOException > exceptions , @ Nullable Collection < IOException > other ) { } }

implementation: if ( exceptions == null ) { return other ; } else if ( other != null ) { exceptions . addAll ( other ) ; } return exceptions ;


signature:
public class MoreFiles { /** * Throws an exception indicating that one or more files couldn ' t be deleted . The thrown exception
 * contains all the exceptions in the given collection as suppressed exceptions . */
private static void throwDeleteFailed ( Path path , Collection < IOException > exceptions ) throws FileSystemException { } }

implementation:
// TODO ( cgdecker ) : Should there be a custom exception type for this ?
// Also , should we try to include the Path of each file we may have failed to delete rather
// than just the exceptions that occurred ?
FileSystemException deleteFailed = new FileSystemException ( path . toString ( ) , null , "failed to delete one or more files; see suppressed exceptions for details" ) ; for ( IOException e : exceptions ) { deleteFailed . addSuppressed ( e ) ; } throw deleteFailed ;


signature:
public class MapMakerInternalMap { /** * Returns a fresh { @ link MapMakerInternalMap } as specified by the given { @ code builder } . */
static < K , V > MapMakerInternalMap < K , V , ? extends InternalEntry < K , V , ? > , ? > create ( MapMaker builder ) { } }

implementation: if ( builder . getKeyStrength ( ) == Strength . STRONG && builder . getValueStrength ( ) == Strength . STRONG ) { return new MapMakerInternalMap < > ( builder , StrongKeyStrongValueEntry . Helper . < K , V > instance ( ) ) ; } if ( builder . getKeyStrength ( ) == Strength . STRONG && builder . getValueStrength ( ) == Strength . WEAK ) { return new MapMakerInternalMap < > ( builder , StrongKeyWeakValueEntry . Helper . < K , V > instance ( ) ) ; } if ( builder . getKeyStrength ( ) == Strength . WEAK && builder . getValueStrength ( ) == Strength . STRONG ) { return new MapMakerInternalMap < > ( builder , WeakKeyStrongValueEntry . Helper . < K , V > instance ( ) ) ; } if ( builder . getKeyStrength ( ) == Strength . WEAK && builder . getValueStrength ( ) == Strength . WEAK ) { return new MapMakerInternalMap < > ( builder , WeakKeyWeakValueEntry . Helper . < K , V > instance ( ) ) ; } throw new AssertionError ( ) ;


signature:
public class MapMakerInternalMap { /** * Returns a fresh { @ link MapMakerInternalMap } with { @ link MapMaker . Dummy } values but otherwise as
 * specified by the given { @ code builder } . The returned { @ link MapMakerInternalMap } will be
 * optimized to saved memory . Since { @ link MapMaker . Dummy } is a singleton , we don ' t need to store
 * any values at all . Because of this optimization , { @ code build . getValueStrength ( ) } must be
 * { @ link Strength # STRONG } .
 * < p > This method is intended to only be used by the internal implementation of { @ link Interners } ,
 * since a map of dummy values is the exact use case there . */
static < K > MapMakerInternalMap < K , Dummy , ? extends InternalEntry < K , Dummy , ? > , ? > createWithDummyValues ( MapMaker builder ) { } }

implementation: if ( builder . getKeyStrength ( ) == Strength . STRONG && builder . getValueStrength ( ) == Strength . STRONG ) { return new MapMakerInternalMap < > ( builder , StrongKeyDummyValueEntry . Helper . < K > instance ( ) ) ; } if ( builder . getKeyStrength ( ) == Strength . WEAK && builder . getValueStrength ( ) == Strength . STRONG ) { return new MapMakerInternalMap < > ( builder , WeakKeyDummyValueEntry . Helper . < K > instance ( ) ) ; } if ( builder . getValueStrength ( ) == Strength . WEAK ) { throw new IllegalArgumentException ( "Map cannot have both weak and dummy values" ) ; } throw new AssertionError ( ) ;


signature:
public class MapMakerInternalMap { /** * Applies a supplemental hash function to a given hash code , which defends against poor quality
 * hash functions . This is critical when the concurrent hash map uses power - of - two length hash
 * tables , that otherwise encounter collisions for hash codes that do not differ in lower or upper
 * bits .
 * @ param h hash code */
static int rehash ( int h ) { } }

implementation:
// Spread bits to regularize both segment and index locations ,
// using variant of single - word Wang / Jenkins hash .
// TODO ( kevinb ) : use Hashing / move this to Hashing ?
h += ( h << 15 ) ^ 0xffffcd7d ; h ^= ( h >>> 10 ) ; h += ( h << 3 ) ; h ^= ( h >>> 6 ) ; h += ( h << 2 ) + ( h << 14 ) ; return h ^ ( h >>> 16 ) ;


signature:
public class MapMakerInternalMap { /** * Guarded By Segment . this */
@ VisibleForTesting E copyEntry ( E original , E newNext ) { } }

implementation: int hash = original . getHash ( ) ; return segmentFor ( hash ) . copyEntry ( original , newNext ) ;


signature:
public class MapMakerInternalMap { /** * Returns the segment that should be used for a key with the given hash .
 * @ param hash the hash code for the key
 * @ return the segment */
Segment < K , V , E , S > segmentFor ( int hash ) { } }

implementation:
// TODO ( fry ) : Lazily create segments ?
return segments [ ( hash >>> segmentShift ) & segmentMask ] ;


signature:
public class MapMakerInternalMap { /** * Gets the value from an entry . Returns { @ code null } if the entry is invalid , partially - collected
 * or computing . */
V getLiveValue ( E entry ) { } }

implementation: if ( entry . getKey ( ) == null ) { return null ; } V value = entry . getValue ( ) ; if ( value == null ) { return null ; } return value ;


signature:
public class MapMakerInternalMap { /** * Returns the internal entry for the specified key . The entry may be computing or partially
 * collected . Does not impact recency ordering . */
E getEntry ( @ Nullable Object key ) { } }

implementation: if ( key == null ) { return null ; } int hash = hash ( key ) ; return segmentFor ( hash ) . getEntry ( key , hash ) ;


signature:
public class ImmutableList { /** * are guaranteed to be non - null . */
static < E > ImmutableList < E > unsafeDelegateList ( List < ? extends E > list ) { } }

implementation: switch ( list . size ( ) ) { case 0 : return of ( ) ; case 1 : return of ( list . get ( 0 ) ) ; default : @ SuppressWarnings ( "unchecked" ) List < E > castedList = ( List < E > ) list ; return new RegularImmutableList < E > ( castedList ) ; }


signature:
public class ImmutableList { /** * Views the array as an immutable list . The array must have only { @ code E } elements .
 * < p > The array must be internally created . */
@ SuppressWarnings ( "unchecked" ) // caller is reponsible for getting this right
static < E > ImmutableList < E > asImmutableList ( Object [ ] elements ) { } }

implementation: return unsafeDelegateList ( ( List ) Arrays . asList ( elements ) ) ;


signature:
public class TreeRangeMap { /** * Computes the coalesced range for the given range + value - does not mutate the map . */
private Range < K > coalescedRange ( Range < K > range , V value ) { } }

implementation: Range < K > coalescedRange = range ; Entry < Cut < K > , RangeMapEntry < K , V > > lowerEntry = entriesByLowerBound . lowerEntry ( range . lowerBound ) ; coalescedRange = coalesce ( coalescedRange , value , lowerEntry ) ; Entry < Cut < K > , RangeMapEntry < K , V > > higherEntry = entriesByLowerBound . floorEntry ( range . upperBound ) ; coalescedRange = coalesce ( coalescedRange , value , higherEntry ) ; return coalescedRange ;


signature:
public class InternetDomainName { /** * Returns the index of the leftmost part of the suffix , or - 1 if not found . Note that the value
 * defined as a suffix may not produce { @ code true } results from { @ link # isPublicSuffix ( ) } or
 * { @ link # isRegistrySuffix ( ) } if the domain ends with an excluded domain pattern such as { @ code
 * " nhs . uk " } .
 * < p > If a { @ code desiredType } is specified , this method only finds suffixes of the given type .
 * Otherwise , it finds the first suffix of any type . */
private int findSuffixOfType ( Optional < PublicSuffixType > desiredType ) { } }

implementation:
final int partsSize = parts . size ( ) ; for ( int i = 0 ; i < partsSize ; i ++ ) { String ancestorName = DOT_JOINER . join ( parts . subList ( i , partsSize ) ) ; if ( matchesType ( desiredType , Optional . fromNullable ( PublicSuffixPatterns . EXACT . get ( ancestorName ) ) ) ) { return i ; } // Excluded domains ( e . g . ! nhs . uk ) use the next highest
// domain as the effective public suffix ( e . g . uk ) .
if ( PublicSuffixPatterns . EXCLUDED . containsKey ( ancestorName ) ) { return i + 1 ; } if ( matchesWildcardSuffixType ( desiredType , ancestorName ) ) { return i ; } } return NO_SUFFIX_FOUND ;


signature:
public class InternetDomainName { /** * Validation method used by { @ code from } to ensure that the domain name is syntactically valid
 * according to RFC 1035.
 * @ return Is the domain name syntactically valid ? */
private static boolean validateSyntax ( List < String > parts ) { } }

implementation:
final int lastIndex = parts . size ( ) - 1 ; // Validate the last part specially , as it has different syntax rules .
if ( ! validatePart ( parts . get ( lastIndex ) , true ) ) { return false ; } for ( int i = 0 ; i < lastIndex ; i ++ ) { String part = parts . get ( i ) ; if ( ! validatePart ( part , false ) ) { return false ; } } return true ;


signature:
public class InternetDomainName { /** * Helper method for { @ link # validateSyntax ( List ) } . Validates that one part of a domain name is
 * valid .
 * @ param part The domain name part to be validated
 * @ param isFinalPart Is this the final ( rightmost ) domain part ?
 * @ return Whether the part is valid */
private static boolean validatePart ( String part , boolean isFinalPart ) { } }

implementation:
// These tests could be collapsed into one big boolean expression , but
// they have been left as independent tests for clarity .
if ( part . length ( ) < 1 || part . length ( ) > MAX_DOMAIN_PART_LENGTH ) { return false ; } /* * GWT claims to support java . lang . Character ' s char - classification methods , but it actually only
 * works for ASCII . So for now , assume any non - ASCII characters are valid . The only place this
 * seems to be documented is here :
 * http : / / osdir . com / ml / GoogleWebToolkitContributors / 2010-03 / msg00178 . html
 * < p > ASCII characters in the part are expected to be valid per RFC 1035 , with underscore also
 * being allowed due to widespread practice . */
String asciiChars = CharMatcher . ascii ( ) . retainFrom ( part ) ; if ( ! PART_CHAR_MATCHER . matchesAllOf ( asciiChars ) ) { return false ; } // No initial or final dashes or underscores .
if ( DASH_MATCHER . matches ( part . charAt ( 0 ) ) || DASH_MATCHER . matches ( part . charAt ( part . length ( ) - 1 ) ) ) { return false ; } /* * Note that we allow ( in contravention of a strict interpretation of the relevant RFCs ) domain
 * parts other than the last may begin with a digit ( for example , " 3com . com " ) . It ' s important to
 * disallow an initial digit in the last part ; it ' s the only thing that stops an IPv4 numeric
 * address like 127.0.0.1 from looking like a valid domain name . */
if ( isFinalPart && CharMatcher . digit ( ) . matches ( part . charAt ( 0 ) ) ) { return false ; } return true ;


signature:
public class InternetDomainName { /** * Returns the ancestor of the current domain at the given number of levels " higher " ( rightward )
 * in the subdomain list . The number of levels must be non - negative , and less than { @ code N - 1 } ,
 * where { @ code N } is the number of parts in the domain .
 * < p > TODO : Reasonable candidate for addition to public API . */
private InternetDomainName ancestor ( int levels ) { } }

implementation: return from ( DOT_JOINER . join ( parts . subList ( levels , parts . size ( ) ) ) ) ;


signature:
public class InternetDomainName { /** * Does the domain name match one of the " wildcard " patterns ( e . g . { @ code " * . ar " } ) ? If a { @ code
 * desiredType } is specified , the wildcard pattern must also match that type . */
private static boolean matchesWildcardSuffixType ( Optional < PublicSuffixType > desiredType , String domain ) { } }

implementation: List < String > pieces = DOT_SPLITTER . limit ( 2 ) . splitToList ( domain ) ; return pieces . size ( ) == 2 && matchesType ( desiredType , Optional . fromNullable ( PublicSuffixPatterns . UNDER . get ( pieces . get ( 1 ) ) ) ) ;


signature:
public class InternetDomainName { /** * If a { @ code desiredType } is specified , returns true only if the { @ code actualType } is
 * identical . Otherwise , returns true as long as { @ code actualType } is present . */
private static boolean matchesType ( Optional < PublicSuffixType > desiredType , Optional < PublicSuffixType > actualType ) { } }

implementation: return desiredType . isPresent ( ) ? desiredType . equals ( actualType ) : actualType . isPresent ( ) ;


signature:
public class SubscriberRegistry { /** * Unregisters all subscribers on the given listener object . */
void unregister ( Object listener ) { } }

implementation:
Multimap < Class < ? > , Subscriber > listenerMethods = findAllSubscribers ( listener ) ; for ( Entry < Class < ? > , Collection < Subscriber > > entry : listenerMethods . asMap ( ) . entrySet ( ) ) { Class < ? > eventType = entry . getKey ( ) ; Collection < Subscriber > listenerMethodsForType = entry . getValue ( ) ; CopyOnWriteArraySet < Subscriber > currentSubscribers = subscribers . get ( eventType ) ; if ( currentSubscribers == null || ! currentSubscribers . removeAll ( listenerMethodsForType ) ) { // if removeAll returns true , all we really know is that at least one subscriber was
// removed . . . however , barring something very strange we can assume that if at least one
// subscriber was removed , all subscribers on listener for that event type were . . . after
// all , the definition of subscribers on a particular class is totally static
throw new IllegalArgumentException ( "missing event subscriber for an annotated method. Is " + listener + " registered?" ) ; } // don ' t try to remove the set if it ' s empty ; that can ' t be done safely without a lock
// anyway , if the set is empty it ' ll just be wrapping an array of length 0
}


signature:
public class SubscriberRegistry { /** * Gets an iterator representing an immutable snapshot of all subscribers to the given event at
 * the time this method is called . */
Iterator < Subscriber > getSubscribers ( Object event ) { } }

implementation:
ImmutableSet < Class < ? > > eventTypes = flattenHierarchy ( event . getClass ( ) ) ; List < Iterator < Subscriber > > subscriberIterators = Lists . newArrayListWithCapacity ( eventTypes . size ( ) ) ; for ( Class < ? > eventType : eventTypes ) { CopyOnWriteArraySet < Subscriber > eventSubscribers = subscribers . get ( eventType ) ; if ( eventSubscribers != null ) { // eager no - copy snapshot
subscriberIterators . add ( eventSubscribers . iterator ( ) ) ; } } return Iterators . concat ( subscriberIterators . iterator ( ) ) ;


signature:
public class SubscriberRegistry { /** * Returns all subscribers for the given listener grouped by the type of event they subscribe to . */
private Multimap < Class < ? > , Subscriber > findAllSubscribers ( Object listener ) { } }

implementation: Multimap < Class < ? > , Subscriber > methodsInListener = HashMultimap . create ( ) ; Class < ? > clazz = listener . getClass ( ) ; for ( Method method : getAnnotatedMethods ( clazz ) ) { Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; Class < ? > eventType = parameterTypes [ 0 ] ; methodsInListener . put ( eventType , Subscriber . create ( bus , listener , method ) ) ; } return methodsInListener ;


signature:
public class SubscriberRegistry { /** * Flattens a class ' s type hierarchy into a set of { @ code Class } objects including all
 * superclasses ( transitively ) and all interfaces implemented by these superclasses . */
@ VisibleForTesting static ImmutableSet < Class < ? > > flattenHierarchy ( Class < ? > concreteClass ) { } }

implementation: try { return flattenHierarchyCache . getUnchecked ( concreteClass ) ; } catch ( UncheckedExecutionException e ) { throw Throwables . propagate ( e . getCause ( ) ) ; }


signature:
public class ImmutableList { /** * Returns an immutable list containing the given elements , in order .
 * < 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 > Note that if { @ code list } is a { @ code List < String > } , then { @ code ImmutableList . copyOf ( list ) }
 * returns an { @ code ImmutableList < String > } containing each of the strings in { @ code list } , while
 * ImmutableList . of ( list ) } returns an { @ code ImmutableList < List < String > > } containing one element
 * ( the given list itself ) .
 * < p > This method is safe to use even when { @ code elements } is a synchronized or concurrent
 * collection that is currently being modified by another thread .
 * @ throws NullPointerException if any of { @ code elements } is null */
public static < E > ImmutableList < E > copyOf ( Collection < ? extends E > elements ) { } }

implementation:
if ( elements instanceof ImmutableCollection ) { @ SuppressWarnings ( "unchecked" ) // all supported methods are covariant
ImmutableList < E > list = ( ( ImmutableCollection < E > ) elements ) . asList ( ) ; return list . isPartialView ( ) ? ImmutableList . < E > asImmutableList ( list . toArray ( ) ) : list ; } return construct ( elements . toArray ( ) ) ;


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

implementation:
// We special - case for 0 or 1 elements , but going further is madness .
if ( ! elements . hasNext ( ) ) { return of ( ) ; } E first = elements . next ( ) ; if ( ! elements . hasNext ( ) ) { return of ( first ) ; } else { return new ImmutableList . Builder < E > ( ) . add ( first ) . addAll ( elements ) . build ( ) ; }


signature:
public class ImmutableList { /** * Returns an immutable list containing the given elements , in order .
 * @ throws NullPointerException if any of { @ code elements } is null
 * @ since 3.0 */
public static < E > ImmutableList < E > copyOf ( E [ ] elements ) { } }

implementation: return ( elements . length == 0 ) ? ImmutableList . < E > of ( ) : ImmutableList . < E > construct ( elements . clone ( ) ) ;


signature:
public class ImmutableList { /** * Returns an immutable list containing the given elements , sorted according to their natural
 * order . The sorting algorithm used is stable , so elements that compare as equal will stay in the
 * order in which they appear in the input .
 * < p > If your data has no duplicates , or you wish to deduplicate elements , use { @ code
 * ImmutableSortedSet . copyOf ( elements ) } ; if you want a { @ code List } you can use its { @ code
 * asList ( ) } view .
 * < p > < b > Java 8 users : < / b > If you want to convert a { @ link java . util . stream . Stream } to a sorted
 * { @ code ImmutableList } , use { @ code stream . sorted ( ) . collect ( toImmutableList ( ) ) } .
 * @ throws NullPointerException if any element in the input is null
 * @ since 21.0 */
public static < E extends Comparable < ? super E > > ImmutableList < E > sortedCopyOf ( Iterable < ? extends E > elements ) { } }

implementation: Comparable < ? > [ ] array = Iterables . toArray ( elements , new Comparable < ? > [ 0 ] ) ; checkElementsNotNull ( ( Object [ ] ) array ) ; Arrays . sort ( array ) ; return asImmutableList ( array ) ;


signature:
public class ImmutableList { /** * Views the array as an immutable list . Does not check for nulls ; does not copy .
 * < p > The array must be internally created . */
static < E > ImmutableList < E > asImmutableList ( Object [ ] elements ) { } }

implementation: return asImmutableList ( elements , elements . length ) ;


signature:
public class ImmutableList { /** * Views the array as an immutable list . Does not check for nulls . */
static < E > ImmutableList < E > asImmutableList ( Object [ ] elements , int length ) { } }

implementation: if ( length == 0 ) { return of ( ) ; } return new RegularImmutableList < E > ( elements , length ) ;


signature:
public class ImmutableList { /** * Returns a new builder , expecting the specified number of elements to be added .
 * < p > If { @ code expectedSize } is exactly the number of elements added to the builder before { @ link
 * Builder # build } is called , the builder is likely to perform better than an unsized { @ link
 * # builder ( ) } would have .
 * < p > It is not specified if any performance benefits apply if { @ code expectedSize } is close to ,
 * but not exactly , the number of elements added to the builder .
 * @ since 23.1 */
@ Beta public static < E > Builder < E > builderWithExpectedSize ( int expectedSize ) { } }

implementation: checkNonnegative ( expectedSize , "expectedSize" ) ; return new ImmutableList . Builder < E > ( expectedSize ) ;


signature:
public class Range { /** * Returns a range that contains all values strictly greater than { @ code lower } and strictly less
 * than { @ code upper } .
 * @ throws IllegalArgumentException if { @ code lower } is greater than < i > or equal to < / i > { @ code
 * upper }
 * @ throws ClassCastException if { @ code lower } and { @ code upper } are not mutually comparable
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > open ( C lower , C upper ) { } }

implementation: return create ( Cut . aboveValue ( lower ) , Cut . belowValue ( upper ) ) ;


signature:
public class Range { /** * Returns a range that contains all values greater than or equal to { @ code lower } and strictly
 * less than { @ code upper } .
 * @ throws IllegalArgumentException if { @ code lower } is greater than { @ code upper }
 * @ throws ClassCastException if { @ code lower } and { @ code upper } are not mutually comparable
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > closedOpen ( C lower , C upper ) { } }

implementation: return create ( Cut . belowValue ( lower ) , Cut . belowValue ( upper ) ) ;


signature:
public class Range { /** * Returns a range that contains all values strictly greater than { @ code lower } and less than or
 * equal to { @ code upper } .
 * @ throws IllegalArgumentException if { @ code lower } is greater than { @ code upper }
 * @ throws ClassCastException if { @ code lower } and { @ code upper } are not mutually comparable
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > openClosed ( C lower , C upper ) { } }

implementation: return create ( Cut . aboveValue ( lower ) , Cut . aboveValue ( upper ) ) ;


signature:
public class Range { /** * Returns a range that contains any value from { @ code lower } to { @ code upper } , where each
 * endpoint may be either inclusive ( closed ) or exclusive ( open ) .
 * @ throws IllegalArgumentException if { @ code lower } is greater than { @ code upper }
 * @ throws ClassCastException if { @ code lower } and { @ code upper } are not mutually comparable
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > range ( C lower , BoundType lowerType , C upper , BoundType upperType ) { } }

implementation: checkNotNull ( lowerType ) ; checkNotNull ( upperType ) ; Cut < C > lowerBound = ( lowerType == BoundType . OPEN ) ? Cut . aboveValue ( lower ) : Cut . belowValue ( lower ) ; Cut < C > upperBound = ( upperType == BoundType . OPEN ) ? Cut . belowValue ( upper ) : Cut . aboveValue ( upper ) ; return create ( lowerBound , upperBound ) ;


signature:
public class Range { /** * Returns a range that contains all values strictly less than { @ code endpoint } .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > lessThan ( C endpoint ) { } }

implementation: return create ( Cut . < C > belowAll ( ) , Cut . belowValue ( endpoint ) ) ;


signature:
public class Range { /** * Returns a range that contains all values less than or equal to { @ code endpoint } .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > atMost ( C endpoint ) { } }

implementation: return create ( Cut . < C > belowAll ( ) , Cut . aboveValue ( endpoint ) ) ;


signature:
public class Range { /** * Returns a range with no lower bound up to the given endpoint , which may be either inclusive
 * ( closed ) or exclusive ( open ) .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > upTo ( C endpoint , BoundType boundType ) { } }

implementation: switch ( boundType ) { case OPEN : return lessThan ( endpoint ) ; case CLOSED : return atMost ( endpoint ) ; default : throw new AssertionError ( ) ; }


signature:
public class Range { /** * Returns a range that contains all values strictly greater than { @ code endpoint } .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > greaterThan ( C endpoint ) { } }

implementation: return create ( Cut . aboveValue ( endpoint ) , Cut . < C > aboveAll ( ) ) ;


signature:
public class Range { /** * Returns a range that contains all values greater than or equal to { @ code endpoint } .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > atLeast ( C endpoint ) { } }

implementation: return create ( Cut . belowValue ( endpoint ) , Cut . < C > aboveAll ( ) ) ;


signature:
public class Range { /** * Returns a range from the given endpoint , which may be either inclusive ( closed ) or exclusive
 * ( open ) , with no upper bound .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > downTo ( C endpoint , BoundType boundType ) { } }

implementation: switch ( boundType ) { case OPEN : return greaterThan ( endpoint ) ; case CLOSED : return atLeast ( endpoint ) ; default : throw new AssertionError ( ) ; }