signature:
public class Range { /** * Returns a range that { @ linkplain Range # contains ( Comparable ) contains } only the given value . The
 * returned range is { @ linkplain BoundType # CLOSED closed } on both ends .
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > singleton ( C value ) { } }

implementation: return closed ( value , value ) ;


signature:
public class Range { /** * Returns the minimal range that { @ linkplain Range # contains ( Comparable ) contains } all of the
 * given values . The returned range is { @ linkplain BoundType # CLOSED closed } on both ends .
 * @ throws ClassCastException if the values are not mutually comparable
 * @ throws NoSuchElementException if { @ code values } is empty
 * @ throws NullPointerException if any of { @ code values } is null
 * @ since 14.0 */
public static < C extends Comparable < ? > > Range < C > encloseAll ( Iterable < C > values ) { } }

implementation: checkNotNull ( values ) ; if ( values instanceof SortedSet ) { SortedSet < ? extends C > set = cast ( values ) ; Comparator < ? > comparator = set . comparator ( ) ; if ( Ordering . natural ( ) . equals ( comparator ) || comparator == null ) { return closed ( set . first ( ) , set . last ( ) ) ; } } Iterator < C > valueIterator = values . iterator ( ) ; C min = checkNotNull ( valueIterator . next ( ) ) ; C max = min ; while ( valueIterator . hasNext ( ) ) { C value = checkNotNull ( valueIterator . next ( ) ) ; min = Ordering . natural ( ) . min ( min , value ) ; max = Ordering . natural ( ) . max ( max , value ) ; } return closed ( min , max ) ;


signature:
public class Range { /** * Returns { @ code true } if { @ code value } is within the bounds of this range . For example , on the
 * range { @ code [ 0 . . 2 ) } , { @ code contains ( 1 ) } returns { @ code true } , while { @ code contains ( 2 ) }
 * returns { @ code false } . */
public boolean contains ( C value ) { } }

implementation:
checkNotNull ( value ) ; // let this throw CCE if there is some trickery going on
return lowerBound . isLessThan ( value ) && ! upperBound . isLessThan ( value ) ;


signature:
public class Range { /** * Returns { @ code true } if every element in { @ code values } is { @ linkplain # contains contained } in
 * this range . */
public boolean containsAll ( Iterable < ? extends C > values ) { } }

implementation:
if ( Iterables . isEmpty ( values ) ) { return true ; } // this optimizes testing equality of two range - backed sets
if ( values instanceof SortedSet ) { SortedSet < ? extends C > set = cast ( values ) ; Comparator < ? > comparator = set . comparator ( ) ; if ( Ordering . natural ( ) . equals ( comparator ) || comparator == null ) { return contains ( set . first ( ) ) && contains ( set . last ( ) ) ; } } for ( C value : values ) { if ( ! contains ( value ) ) { return false ; } } return true ;


signature:
public class Range { /** * Returns { @ code true } if the bounds of { @ code other } do not extend outside the bounds of this
 * range . Examples :
 * < ul >
 * < li > { @ code [ 3 . . 6 ] } encloses { @ code [ 4 . . 5 ] }
 * < li > { @ code ( 3 . . 6 ) } encloses { @ code ( 3 . . 6 ) }
 * < li > { @ code [ 3 . . 6 ] } encloses { @ code [ 4 . . 4 ) } ( even though the latter is empty )
 * < li > { @ code ( 3 . . 6 ] } does not enclose { @ code [ 3 . . 6 ] }
 * < li > { @ code [ 4 . . 5 ] } does not enclose { @ code ( 3 . . 6 ) } ( even though it contains every value
 * contained by the latter range )
 * < li > { @ code [ 3 . . 6 ] } does not enclose { @ code ( 1 . . 1 ] } ( even though it contains every value
 * contained by the latter range )
 * < / ul >
 * < p > Note that if { @ code a . encloses ( b ) } , then { @ code b . contains ( v ) } implies { @ code
 * a . contains ( v ) } , but as the last two examples illustrate , the converse is not always true .
 * < p > Being reflexive , antisymmetric and transitive , the { @ code encloses } relation defines a
 * < i > partial order < / i > over ranges . There exists a unique { @ linkplain Range # all maximal } range
 * according to this relation , and also numerous { @ linkplain # isEmpty minimal } ranges . Enclosure
 * also implies { @ linkplain # isConnected connectedness } . */
public boolean encloses ( Range < C > other ) { } }

implementation: return lowerBound . compareTo ( other . lowerBound ) <= 0 && upperBound . compareTo ( other . upperBound ) >= 0 ;


signature:
public class Range { /** * Returns { @ code true } if there exists a ( possibly empty ) range which is { @ linkplain # encloses
 * enclosed } by both this range and { @ code other } .
 * < p > For example ,
 * < ul >
 * < li > { @ code [ 2 , 4 ) } and { @ code [ 5 , 7 ) } are not connected
 * < li > { @ code [ 2 , 4 ) } and { @ code [ 3 , 5 ) } are connected , because both enclose { @ code [ 3 , 4 ) }
 * < li > { @ code [ 2 , 4 ) } and { @ code [ 4 , 6 ) } are connected , because both enclose the empty range
 * { @ code [ 4 , 4 ) }
 * < / ul >
 * < p > Note that this range and { @ code other } have a well - defined { @ linkplain # span union } and
 * { @ linkplain # intersection intersection } ( as a single , possibly - empty range ) if and only if this
 * method returns { @ code true } .
 * < p > The connectedness relation is both reflexive and symmetric , but does not form an { @ linkplain
 * Equivalence equivalence relation } as it is not transitive .
 * < p > Note that certain discrete ranges are not considered connected , even though there are no
 * elements " between them . " For example , { @ code [ 3 , 5 ] } is not considered connected to { @ code [ 6,
 * 10 ] } . In these cases , it may be desirable for both input ranges to be preprocessed with { @ link
 * # canonical ( DiscreteDomain ) } before testing for connectedness . */
public boolean isConnected ( Range < C > other ) { } }

implementation: return lowerBound . compareTo ( other . upperBound ) <= 0 && other . lowerBound . compareTo ( upperBound ) <= 0 ;


signature:
public class Range { /** * Returns the maximal range { @ linkplain # encloses enclosed } by both this range and { @ code
 * connectedRange } , if such a range exists .
 * < p > For example , the intersection of { @ code [ 1 . . 5 ] } and { @ code ( 3 . . 7 ) } is { @ code ( 3 . . 5 ] } . The
 * resulting range may be empty ; for example , { @ code [ 1 . . 5 ) } intersected with { @ code [ 5 . . 7 ) }
 * yields the empty range { @ code [ 5 . . 5 ) } .
 * < p > The intersection exists if and only if the two ranges are { @ linkplain # isConnected
 * connected } .
 * < p > The intersection operation is commutative , associative and idempotent , and its identity
 * element is { @ link Range # all } ) .
 * @ throws IllegalArgumentException if { @ code isConnected ( connectedRange ) } is { @ code false } */
public Range < C > intersection ( Range < C > connectedRange ) { } }

implementation: int lowerCmp = lowerBound . compareTo ( connectedRange . lowerBound ) ; int upperCmp = upperBound . compareTo ( connectedRange . upperBound ) ; if ( lowerCmp >= 0 && upperCmp <= 0 ) { return this ; } else if ( lowerCmp <= 0 && upperCmp >= 0 ) { return connectedRange ; } else { Cut < C > newLower = ( lowerCmp >= 0 ) ? lowerBound : connectedRange . lowerBound ; Cut < C > newUpper = ( upperCmp <= 0 ) ? upperBound : connectedRange . upperBound ; return create ( newLower , newUpper ) ; }


signature:
public class Range { /** * Returns the maximal range lying between this range and { @ code otherRange } , if such a range
 * exists . The resulting range may be empty if the two ranges are adjacent but non - overlapping .
 * < p > For example , the gap of { @ code [ 1 . . 5 ] } and { @ code ( 7 . . 10 ) } is { @ code ( 5 . . 7 ] } . The resulting
 * range may be empty ; for example , the gap between { @ code [ 1 . . 5 ) } { @ code [ 5 . . 7 ) } yields the empty
 * range { @ code [ 5 . . 5 ) } .
 * < p > The gap exists if and only if the two ranges are either disconnected or immediately adjacent
 * ( any intersection must be an empty range ) .
 * < p > The gap operation is commutative .
 * @ throws IllegalArgumentException if this range and { @ code otherRange } have a nonempty
 * intersection
 * @ since 27.0 */
public Range < C > gap ( Range < C > otherRange ) { } }

implementation: boolean isThisFirst = this . lowerBound . compareTo ( otherRange . lowerBound ) < 0 ; Range < C > firstRange = isThisFirst ? this : otherRange ; Range < C > secondRange = isThisFirst ? otherRange : this ; return create ( firstRange . upperBound , secondRange . lowerBound ) ;


signature:
public class Range { /** * Returns the minimal range that { @ linkplain # encloses encloses } both this range and { @ code
 * other } . For example , the span of { @ code [ 1 . . 3 ] } and { @ code ( 5 . . 7 ) } is { @ code [ 1 . . 7 ) } .
 * < p > < i > If < / i > the input ranges are { @ linkplain # isConnected connected } , the returned range can
 * also be called their < i > union < / i > . If they are not , note that the span might contain values
 * that are not contained in either input range .
 * < p > Like { @ link # intersection ( Range ) intersection } , this operation is commutative , associative
 * and idempotent . Unlike it , it is always well - defined for any two input ranges . */
public Range < C > span ( Range < C > other ) { } }

implementation: int lowerCmp = lowerBound . compareTo ( other . lowerBound ) ; int upperCmp = upperBound . compareTo ( other . upperBound ) ; if ( lowerCmp <= 0 && upperCmp >= 0 ) { return this ; } else if ( lowerCmp >= 0 && upperCmp <= 0 ) { return other ; } else { Cut < C > newLower = ( lowerCmp <= 0 ) ? lowerBound : other . lowerBound ; Cut < C > newUpper = ( upperCmp >= 0 ) ? upperBound : other . upperBound ; return create ( newLower , newUpper ) ; }


signature:
public class Range { /** * Returns the canonical form of this range in the given domain . The canonical form has the
 * following properties :
 * < ul >
 * < li > equivalence : { @ code a . canonical ( ) . contains ( v ) = = a . contains ( v ) } for all { @ code v } ( in
 * other words , { @ code ContiguousSet . create ( a . canonical ( domain ) , domain ) . equals (
 * ContiguousSet . create ( a , domain ) ) }
 * < li > uniqueness : unless { @ code a . isEmpty ( ) } , { @ code ContiguousSet . create ( a ,
 * domain ) . equals ( ContiguousSet . create ( b , domain ) ) } implies { @ code
 * a . canonical ( domain ) . equals ( b . canonical ( domain ) ) }
 * < li > idempotence : { @ code a . canonical ( domain ) . canonical ( domain ) . equals ( a . canonical ( domain ) ) }
 * < / ul >
 * < p > Furthermore , this method guarantees that the range returned will be one of the following
 * canonical forms :
 * < ul >
 * < li > [ start . . end )
 * < li > [ start . . + ∞ )
 * < li > ( - ∞ . . end ) ( only if type { @ code C } is unbounded below )
 * < li > ( - ∞ . . + ∞ ) ( only if type { @ code C } is unbounded below )
 * < / ul > */
public Range < C > canonical ( DiscreteDomain < C > domain ) { } }

implementation: checkNotNull ( domain ) ; Cut < C > lower = lowerBound . canonical ( domain ) ; Cut < C > upper = upperBound . canonical ( domain ) ; return ( lower == lowerBound && upper == upperBound ) ? this : create ( lower , upper ) ;


signature:
public class Range { /** * Used to avoid http : / / bugs . sun . com / view _ bug . do ? bug _ id = 6558557 */
private static < T > SortedSet < T > cast ( Iterable < T > iterable ) { } }

implementation: return ( SortedSet < T > ) iterable ;


signature:
public class ObjectArrays { /** * Returns a new array of the given length with the same type as a reference array .
 * @ param reference any array of the desired type
 * @ param length the length of the new array */
public static < T > T [ ] newArray ( T [ ] reference , int length ) { } }

implementation: return Platform . newArray ( reference , length ) ;


signature:
public class ObjectArrays { /** * Returns a new array that contains the concatenated contents of two arrays .
 * @ param first the first array of elements to concatenate
 * @ param second the second array of elements to concatenate
 * @ param type the component type of the returned array */
@ GwtIncompatible // Array . newInstance ( Class , int )
public static < T > T [ ] concat ( T [ ] first , T [ ] second , Class < T > type ) { } }

implementation: T [ ] result = newArray ( type , first . length + second . length ) ; System . arraycopy ( first , 0 , result , 0 , first . length ) ; System . arraycopy ( second , 0 , result , first . length , second . length ) ; return result ;


signature:
public class ObjectArrays { /** * Returns a new array that appends { @ code element } to { @ code array } .
 * @ param array the array of elements to prepend
 * @ param element the element to append to the end
 * @ return an array whose size is one larger than { @ code array } , with the same contents as { @ code
 * array } , plus { @ code element } occupying the last position . */
public static < T > T [ ] concat ( T [ ] array , @ Nullable T element ) { } }

implementation: T [ ] result = Arrays . copyOf ( array , array . length + 1 ) ; result [ array . length ] = element ; return result ;


signature:
public class ObjectArrays { /** * Returns an array containing all of the elements in the specified collection ; the runtime type
 * of the returned array is that of the specified array . If the collection fits in the specified
 * array , it is returned therein . Otherwise , a new array is allocated with the runtime type of the
 * specified array and the size of the specified collection .
 * < p > If the collection fits in the specified array with room to spare ( i . e . , the array has more
 * elements than the collection ) , the element in the array immediately following the end of the
 * collection is set to { @ code null } . This is useful in determining the length of the collection
 * < i > only < / i > if the caller knows that the collection does not contain any null elements .
 * < p > This method returns the elements in the order they are returned by the collection ' s
 * iterator .
 * < p > TODO ( kevinb ) : support concurrently modified collections ?
 * @ param c the collection for which to return an array of elements
 * @ param array the array in which to place the collection elements
 * @ throws ArrayStoreException if the runtime type of the specified array is not a supertype of
 * the runtime type of every element in the specified collection */
static < T > T [ ] toArrayImpl ( Collection < ? > c , T [ ] array ) { } }

implementation: int size = c . size ( ) ; if ( array . length < size ) { array = newArray ( array , size ) ; } fillArray ( c , array ) ; if ( array . length > size ) { array [ size ] = null ; } return array ;


signature:
public class ObjectArrays { /** * Implementation of { @ link Collection # toArray ( Object [ ] ) } for collections backed by an object
 * array . the runtime type of the returned array is that of the specified array . If the collection
 * fits in the specified array , it is returned therein . Otherwise , a new array is allocated with
 * the runtime type of the specified array and the size of the specified collection .
 * < p > If the collection fits in the specified array with room to spare ( i . e . , the array has more
 * elements than the collection ) , the element in the array immediately following the end of the
 * collection is set to { @ code null } . This is useful in determining the length of the collection
 * < i > only < / i > if the caller knows that the collection does not contain any null elements . */
static < T > T [ ] toArrayImpl ( Object [ ] src , int offset , int len , T [ ] dst ) { } }

implementation: checkPositionIndexes ( offset , offset + len , src . length ) ; if ( dst . length < len ) { dst = newArray ( dst , len ) ; } else if ( dst . length > len ) { dst [ len ] = null ; } System . arraycopy ( src , offset , dst , 0 , len ) ; return dst ;


signature:
public class ObjectArrays { /** * Returns a copy of the specified subrange of the specified array that is literally an Object [ ] ,
 * and not e . g . a { @ code String [ ] } . */
static Object [ ] copyAsObjectArray ( Object [ ] elements , int offset , int length ) { } }

implementation: checkPositionIndexes ( offset , offset + length , elements . length ) ; if ( length == 0 ) { return new Object [ 0 ] ; } Object [ ] result = new Object [ length ] ; System . arraycopy ( elements , offset , result , 0 , length ) ; return result ;


signature:
public class ObjectArrays { /** * creation cost . */
@ CanIgnoreReturnValue static Object checkElementNotNull ( Object element , int index ) { } }

implementation: if ( element == null ) { throw new NullPointerException ( "at index " + index ) ; } return element ;


signature:
public class ClassPath { /** * Returns a { @ code ClassPath } representing all classes and resources loadable from { @ code
 * classloader } and its ancestor class loaders .
 * < p > < b > Warning : < / b > { @ code ClassPath } can find classes and resources only from :
 * < ul >
 * < li > { @ link URLClassLoader } instances ' { @ code file : } URLs
 * < li > the { @ linkplain ClassLoader # getSystemClassLoader ( ) system class loader } . To search the
 * system class loader even when it is not a { @ link URLClassLoader } ( as in Java 9 ) , { @ code
 * ClassPath } searches the files from the { @ code java . class . path } system property .
 * < / ul >
 * @ throws IOException if the attempt to read class path resources ( jar files or directories )
 * failed . */
public static ClassPath from ( ClassLoader classloader ) throws IOException { } }

implementation: DefaultScanner scanner = new DefaultScanner ( ) ; scanner . scan ( classloader ) ; return new ClassPath ( scanner . getResources ( ) ) ;


signature:
public class ClassPath { /** * Returns all top level classes whose package name is { @ code packageName } . */
public ImmutableSet < ClassInfo > getTopLevelClasses ( String packageName ) { } }

implementation: checkNotNull ( packageName ) ; ImmutableSet . Builder < ClassInfo > builder = ImmutableSet . builder ( ) ; for ( ClassInfo classInfo : getTopLevelClasses ( ) ) { if ( classInfo . getPackageName ( ) . equals ( packageName ) ) { builder . add ( classInfo ) ; } } return builder . build ( ) ;


signature:
public class ClassPath { /** * Returns all top level classes whose package name is { @ code packageName } or starts with { @ code
 * packageName } followed by a ' . ' . */
public ImmutableSet < ClassInfo > getTopLevelClassesRecursive ( String packageName ) { } }

implementation: checkNotNull ( packageName ) ; String packagePrefix = packageName + '.' ; ImmutableSet . Builder < ClassInfo > builder = ImmutableSet . builder ( ) ; for ( ClassInfo classInfo : getTopLevelClasses ( ) ) { if ( classInfo . getName ( ) . startsWith ( packagePrefix ) ) { builder . add ( classInfo ) ; } } return builder . build ( ) ;


signature:
public class ClassPath { /** * TODO ( benyu ) : Try java . nio . file . Paths # get ( ) when Guava drops JDK 6 support . */
@ VisibleForTesting static File toFile ( URL url ) { } }

implementation:
checkArgument ( url . getProtocol ( ) . equals ( "file" ) ) ; try { return new File ( url . toURI ( ) ) ; // Accepts escaped characters like % 20.
} catch ( URISyntaxException e ) { // URL . toURI ( ) doesn ' t escape chars .
return new File ( url . getPath ( ) ) ; // Accepts non - escaped chars like space .
}


signature:
public class Throwables { /** * Propagates { @ code throwable } exactly as - is , if and only if it is an instance of { @ link
 * RuntimeException } or { @ link Error } . Example usage :
 * < pre >
 * try {
 * someMethodThatCouldThrowAnything ( ) ;
 * } catch ( IKnowWhatToDoWithThisException e ) {
 * handle ( e ) ;
 * } catch ( Throwable t ) {
 * Throwables . propagateIfPossible ( t ) ;
 * throw new RuntimeException ( " unexpected " , t ) ;
 * < / pre >
 * @ deprecated Use { @ link # throwIfUnchecked } , which has the same behavior but rejects { @ code
 * null } . */
@ Deprecated @ GwtIncompatible public static void propagateIfPossible ( @ NullableDecl Throwable throwable ) { } }

implementation: if ( throwable != null ) { throwIfUnchecked ( throwable ) ; }


signature:
public class Throwables { /** * Returns the JavaLangAccess class that is present in all Sun JDKs . It is not allowed in
 * AppEngine , and not present in non - Sun JDKs . */
@ GwtIncompatible // java . lang . reflect
@ NullableDecl private static Object getJLA ( ) { } }

implementation:
try { /* * We load sun . misc . * classes using reflection since Android doesn ' t support these classes and
 * would result in compilation failure if we directly refer to these classes . */
Class < ? > sharedSecrets = Class . forName ( SHARED_SECRETS_CLASSNAME , false , null ) ; Method langAccess = sharedSecrets . getMethod ( "getJavaLangAccess" ) ; return langAccess . invoke ( null ) ; } catch ( ThreadDeath death ) { throw death ; } catch ( Throwable t ) { /* * This is not one of AppEngine ' s allowed classes , so even in Sun JDKs , this can fail with
 * a NoClassDefFoundError . Other apps might deny access to sun . misc packages . */
return null ; }


signature:
public class Throwables { /** * Returns the Method that can be used to return the size of a stack , or null if that method
 * cannot be found ( it is only to be found in fairly recent JDKs ) . Tries to test method { @ link
 * sun . misc . JavaLangAccess # getStackTraceDepth ( Throwable ) } getStackTraceDepth } prior to return it
 * ( might fail some JDKs ) .
 * < p > See < a href = " https : / / github . com / google / guava / issues / 2887 " > Throwables # lazyStackTrace throws
 * UnsupportedOperationException < / a > . */
@ GwtIncompatible // java . lang . reflect
@ NullableDecl private static Method getSizeMethod ( ) { } }

implementation: try { Method getStackTraceDepth = getJlaMethod ( "getStackTraceDepth" , Throwable . class ) ; if ( getStackTraceDepth == null ) { return null ; } getStackTraceDepth . invoke ( getJLA ( ) , new Throwable ( ) ) ; return getStackTraceDepth ; } catch ( UnsupportedOperationException | IllegalAccessException | InvocationTargetException e ) { return null ; }


signature:
public class TypeToken { /** * Returns an instance of type token that wraps { @ code type } . */
public static < T > TypeToken < T > of ( Class < T > type ) { } }

implementation: return new SimpleTypeToken < T > ( type ) ;


signature:
public class TypeToken { /** * Returns the raw type of { @ code T } . Formally speaking , if { @ code T } is returned by { @ link
 * java . lang . reflect . Method # getGenericReturnType } , the raw type is what ' s returned by { @ link
 * java . lang . reflect . Method # getReturnType } of the same method object . Specifically :
 * < ul >
 * < li > If { @ code T } is a { @ code Class } itself , { @ code T } itself is returned .
 * < li > If { @ code T } is a { @ link ParameterizedType } , the raw type of the parameterized type is
 * returned .
 * < li > If { @ code T } is a { @ link GenericArrayType } , the returned type is the corresponding array
 * class . For example : { @ code List < Integer > [ ] = > List [ ] } .
 * < li > If { @ code T } is a type variable or a wildcard type , the raw type of the first upper bound
 * is returned . For example : { @ code < X extends Foo > = > Foo } .
 * < / ul > */
public final Class < ? super T > getRawType ( ) { } }

implementation:
// For wildcard or type variable , the first bound determines the runtime type .
Class < ? > rawType = getRawTypes ( ) . iterator ( ) . next ( ) ; @ SuppressWarnings ( "unchecked" ) // raw type is | T |
Class < ? super T > result = ( Class < ? super T > ) rawType ; return result ;


signature:
public class TypeToken { /** * Returns a new { @ code TypeToken } where type variables represented by { @ code typeParam } are
 * substituted by { @ code typeArg } . For example , it can be used to construct { @ code Map < K , V > } for
 * any { @ code K } and { @ code V } type :
 * < pre > { @ code
 * static < K , V > TypeToken < Map < K , V > > mapOf (
 * TypeToken < K > keyType , TypeToken < V > valueType ) {
 * return new TypeToken < Map < K , V > > ( ) { }
 * . where ( new TypeParameter < K > ( ) { } , keyType )
 * . where ( new TypeParameter < V > ( ) { } , valueType ) ;
 * } < / pre >
 * @ param < X > The parameter type
 * @ param typeParam the parameter type variable
 * @ param typeArg the actual type to substitute */
public final < X > TypeToken < T > where ( TypeParameter < X > typeParam , TypeToken < X > typeArg ) { } }

implementation:
TypeResolver resolver = new TypeResolver ( ) . where ( ImmutableMap . of ( new TypeResolver . TypeVariableKey ( typeParam . typeVariable ) , typeArg . runtimeType ) ) ; // If there ' s any type error , we ' d report now rather than later .
return new SimpleTypeToken < T > ( resolver . resolveType ( runtimeType ) ) ;


signature:
public class TypeToken { /** * Returns a new { @ code TypeToken } where type variables represented by { @ code typeParam } are
 * substituted by { @ code typeArg } . For example , it can be used to construct { @ code Map < K , V > } for
 * any { @ code K } and { @ code V } type :
 * < pre > { @ code
 * static < K , V > TypeToken < Map < K , V > > mapOf (
 * Class < K > keyType , Class < V > valueType ) {
 * return new TypeToken < Map < K , V > > ( ) { }
 * . where ( new TypeParameter < K > ( ) { } , keyType )
 * . where ( new TypeParameter < V > ( ) { } , valueType ) ;
 * } < / pre >
 * @ param < X > The parameter type
 * @ param typeParam the parameter type variable
 * @ param typeArg the actual type to substitute */
public final < X > TypeToken < T > where ( TypeParameter < X > typeParam , Class < X > typeArg ) { } }

implementation: return where ( typeParam , of ( typeArg ) ) ;


signature:
public class TypeToken { /** * Resolves the given { @ code type } against the type context represented by this type . For example :
 * < pre > { @ code
 * new TypeToken < List < String > > ( ) { } . resolveType (
 * List . class . getMethod ( " get " , int . class ) . getGenericReturnType ( ) )
 * = > String . class
 * } < / pre > */
public final TypeToken < ? > resolveType ( Type type ) { } }

implementation:
checkNotNull ( type ) ; // Being conservative here because the user could use resolveType ( ) to resolve a type in an
// invariant context .
return of ( getInvariantTypeResolver ( ) . resolveType ( type ) ) ;


signature:
public class TypeToken { /** * Returns the generic interfaces that this type directly { @ code implements } . This method is
 * similar but different from { @ link Class # getGenericInterfaces ( ) } . For example , { @ code new
 * TypeToken < List < String > > ( ) { } . getGenericInterfaces ( ) } will return a list that contains { @ code
 * new TypeToken < Iterable < String > > ( ) { } } ; while { @ code List . class . getGenericInterfaces ( ) } will
 * return an array that contains { @ code Iterable < T > } , where the { @ code T } is the type variable
 * declared by interface { @ code Iterable } .
 * < p > If this type is a type variable or wildcard , its upper bounds are examined and those that
 * are either an interface or upper - bounded only by interfaces are returned . This means that the
 * returned types could include type variables too . */
final ImmutableList < TypeToken < ? super T > > getGenericInterfaces ( ) { } }

implementation:
if ( runtimeType instanceof TypeVariable ) { return boundsAsInterfaces ( ( ( TypeVariable < ? > ) runtimeType ) . getBounds ( ) ) ; } if ( runtimeType instanceof WildcardType ) { return boundsAsInterfaces ( ( ( WildcardType ) runtimeType ) . getUpperBounds ( ) ) ; } ImmutableList . Builder < TypeToken < ? super T > > builder = ImmutableList . builder ( ) ; for ( Type interfaceType : getRawType ( ) . getGenericInterfaces ( ) ) { @ SuppressWarnings ( "unchecked" ) // interface of T
TypeToken < ? super T > resolvedInterface = ( TypeToken < ? super T > ) resolveSupertype ( interfaceType ) ; builder . add ( resolvedInterface ) ; } return builder . build ( ) ;


signature:
public class TypeToken { /** * Returns the generic form of { @ code superclass } . For example , if this is { @ code
 * ArrayList < String > } , { @ code Iterable < String > } is returned given the input { @ code
 * Iterable . class } . */
public final TypeToken < ? super T > getSupertype ( Class < ? super T > superclass ) { } }

implementation:
checkArgument ( this . someRawTypeIsSubclassOf ( superclass ) , "%s is not a super class of %s" , superclass , this ) ; if ( runtimeType instanceof TypeVariable ) { return getSupertypeFromUpperBounds ( superclass , ( ( TypeVariable < ? > ) runtimeType ) . getBounds ( ) ) ; } if ( runtimeType instanceof WildcardType ) { return getSupertypeFromUpperBounds ( superclass , ( ( WildcardType ) runtimeType ) . getUpperBounds ( ) ) ; } if ( superclass . isArray ( ) ) { return getArraySupertype ( superclass ) ; } @ SuppressWarnings ( "unchecked" ) // resolved supertype
TypeToken < ? super T > supertype = ( TypeToken < ? super T > ) resolveSupertype ( toGenericType ( superclass ) . runtimeType ) ; return supertype ;


signature:
public class TypeToken { /** * Returns subtype of { @ code this } with { @ code subclass } as the raw class . For example , if this is
 * { @ code Iterable < String > } and { @ code subclass } is { @ code List } , { @ code List < String > } is
 * returned . */
public final TypeToken < ? extends T > getSubtype ( Class < ? > subclass ) { } }

implementation:
checkArgument ( ! ( runtimeType instanceof TypeVariable ) , "Cannot get subtype of type variable <%s>" , this ) ; if ( runtimeType instanceof WildcardType ) { return getSubtypeFromLowerBounds ( subclass , ( ( WildcardType ) runtimeType ) . getLowerBounds ( ) ) ; } // unwrap array type if necessary
if ( isArray ( ) ) { return getArraySubtype ( subclass ) ; } // At this point , it ' s either a raw class or parameterized type .
checkArgument ( getRawType ( ) . isAssignableFrom ( subclass ) , "%s isn't a subclass of %s" , subclass , this ) ; Type resolvedTypeArgs = resolveTypeArgsForSubclass ( subclass ) ; @ SuppressWarnings ( "unchecked" ) // guarded by the isAssignableFrom ( ) statement above
TypeToken < ? extends T > subtype = ( TypeToken < ? extends T > ) of ( resolvedTypeArgs ) ; checkArgument ( subtype . isSubtypeOf ( this ) , "%s does not appear to be a subtype of %s" , subtype , this ) ; return subtype ;


signature:
public class TypeToken { /** * Returns true if this type is a subtype of the given { @ code type } . " Subtype " is defined
 * according to < a
 * href = " http : / / docs . oracle . com / javase / specs / jls / se8 / html / jls - 4 . html # jls - 4.5.1 " > the rules for type
 * arguments < / a > introduced with Java generics .
 * @ since 19.0 */
public final boolean isSubtypeOf ( Type supertype ) { } }

implementation:
checkNotNull ( supertype ) ; if ( supertype instanceof WildcardType ) { // if ' supertype ' is < ? super Foo > , ' this ' can be :
// Foo , SubFoo , < ? extends Foo > .
// if ' supertype ' is < ? extends Foo > , nothing is a subtype .
return any ( ( ( WildcardType ) supertype ) . getLowerBounds ( ) ) . isSupertypeOf ( runtimeType ) ; } // if ' this ' is wildcard , it ' s a suptype of to ' supertype ' if any of its " extends "
// bounds is a subtype of ' supertype ' .
if ( runtimeType instanceof WildcardType ) { // < ? super Base > is of no use in checking ' from ' being a subtype of ' to ' .
return any ( ( ( WildcardType ) runtimeType ) . getUpperBounds ( ) ) . isSubtypeOf ( supertype ) ; } // if ' this ' is type variable , it ' s a subtype if any of its " extends "
// bounds is a subtype of ' supertype ' .
if ( runtimeType instanceof TypeVariable ) { return runtimeType . equals ( supertype ) || any ( ( ( TypeVariable < ? > ) runtimeType ) . getBounds ( ) ) . isSubtypeOf ( supertype ) ; } if ( runtimeType instanceof GenericArrayType ) { return of ( supertype ) . isSupertypeOfArray ( ( GenericArrayType ) runtimeType ) ; } // Proceed to regular Type subtype check
if ( supertype instanceof Class ) { return this . someRawTypeIsSubclassOf ( ( Class < ? > ) supertype ) ; } else if ( supertype instanceof ParameterizedType ) { return this . isSubtypeOfParameterizedType ( ( ParameterizedType ) supertype ) ; } else if ( supertype instanceof GenericArrayType ) { return this . isSubtypeOfArrayType ( ( GenericArrayType ) supertype ) ; } else { // to instanceof TypeVariable
return false ; }


signature:
public class TypeToken { /** * Returns the corresponding wrapper type if this is a primitive type ; otherwise returns { @ code
 * this } itself . Idempotent .
 * @ since 15.0 */
public final TypeToken < T > wrap ( ) { } }

implementation:
if ( isPrimitive ( ) ) { @ SuppressWarnings ( "unchecked" ) // this is a primitive class
Class < T > type = ( Class < T > ) runtimeType ; return of ( Primitives . wrap ( type ) ) ; } return this ;


signature:
public class TypeToken { /** * Returns the corresponding primitive type if this is a wrapper type ; otherwise returns { @ code
 * this } itself . Idempotent .
 * @ since 15.0 */
public final TypeToken < T > unwrap ( ) { } }

implementation:
if ( isWrapper ( ) ) { @ SuppressWarnings ( "unchecked" ) // this is a wrapper class
Class < T > type = ( Class < T > ) runtimeType ; return of ( Primitives . unwrap ( type ) ) ; } return this ;


signature:
public class TypeToken { /** * Returns the { @ link Invokable } for { @ code method } , which must be a member of { @ code T } .
 * @ since 14.0 */
public final Invokable < T , Object > method ( Method method ) { } }

implementation: checkArgument ( this . someRawTypeIsSubclassOf ( method . getDeclaringClass ( ) ) , "%s not declared by %s" , method , this ) ; return new Invokable . MethodInvokable < T > ( method ) { @ Override Type getGenericReturnType ( ) { return getCovariantTypeResolver ( ) . resolveType ( super . getGenericReturnType ( ) ) ; } @ Override Type [ ] getGenericParameterTypes ( ) { return getInvariantTypeResolver ( ) . resolveTypesInPlace ( super . getGenericParameterTypes ( ) ) ; } @ Override Type [ ] getGenericExceptionTypes ( ) { return getCovariantTypeResolver ( ) . resolveTypesInPlace ( super . getGenericExceptionTypes ( ) ) ; } @ Override public TypeToken < T > getOwnerType ( ) { return TypeToken . this ; } @ Override public String toString ( ) { return getOwnerType ( ) + "." + super . toString ( ) ; } } ;


signature:
public class TypeToken { /** * Returns the { @ link Invokable } for { @ code constructor } , which must be a member of { @ code T } .
 * @ since 14.0 */
public final Invokable < T , T > constructor ( Constructor < ? > constructor ) { } }

implementation: checkArgument ( constructor . getDeclaringClass ( ) == getRawType ( ) , "%s not declared by %s" , constructor , getRawType ( ) ) ; return new Invokable . ConstructorInvokable < T > ( constructor ) { @ Override Type getGenericReturnType ( ) { return getCovariantTypeResolver ( ) . resolveType ( super . getGenericReturnType ( ) ) ; } @ Override Type [ ] getGenericParameterTypes ( ) { return getInvariantTypeResolver ( ) . resolveTypesInPlace ( super . getGenericParameterTypes ( ) ) ; } @ Override Type [ ] getGenericExceptionTypes ( ) { return getCovariantTypeResolver ( ) . resolveTypesInPlace ( super . getGenericExceptionTypes ( ) ) ; } @ Override public TypeToken < T > getOwnerType ( ) { return TypeToken . this ; } @ Override public String toString ( ) { return getOwnerType ( ) + "(" + Joiner . on ( ", " ) . join ( getGenericParameterTypes ( ) ) + ")" ; } } ;


signature:
public class TypeToken { /** * Ensures that this type token doesn ' t contain type variables , which can cause unchecked type
 * errors for callers like { @ link TypeToInstanceMap } . */
@ CanIgnoreReturnValue final TypeToken < T > rejectTypeVariables ( ) { } }

implementation: new TypeVisitor ( ) { @ Override void visitTypeVariable ( TypeVariable < ? > type ) { throw new IllegalArgumentException ( runtimeType + "contains a type variable and is not safe for the operation" ) ; } @ Override void visitWildcardType ( WildcardType type ) { visit ( type . getLowerBounds ( ) ) ; visit ( type . getUpperBounds ( ) ) ; } @ Override void visitParameterizedType ( ParameterizedType type ) { visit ( type . getActualTypeArguments ( ) ) ; visit ( type . getOwnerType ( ) ) ; } @ Override void visitGenericArrayType ( GenericArrayType type ) { visit ( type . getGenericComponentType ( ) ) ; } } . visit ( runtimeType ) ; return this ;


signature:
public class TypeToken { /** * { @ code A . is ( B ) } is defined as { @ code Foo < A > . isSubtypeOf ( Foo < B > ) } .
 * < p > Specifically , returns true if any of the following conditions is met :
 * < ol >
 * < li > ' this ' and { @ code formalType } are equal .
 * < li > ' this ' and { @ code formalType } have equal canonical form .
 * < li > { @ code formalType } is { @ code < ? extends Foo > } and ' this ' is a subtype of { @ code Foo } .
 * < li > { @ code formalType } is { @ code < ? super Foo > } and ' this ' is a supertype of { @ code Foo } .
 * < / ol >
 * Note that condition 2 isn ' t technically accurate under the context of a recursively bounded
 * type variables . For example , { @ code Enum < ? extends Enum < E > > } canonicalizes to { @ code Enum < ? > }
 * where { @ code E } is the type variable declared on the { @ code Enum } class declaration . It ' s
 * technically < em > not < / em > true that { @ code Foo < Enum < ? extends Enum < E > > > } is a subtype of { @ code
 * Foo < Enum < ? > > } according to JLS . See testRecursiveWildcardSubtypeBug ( ) for a real example .
 * < p > It appears that properly handling recursive type bounds in the presence of implicit type
 * bounds is not easy . For now we punt , hoping that this defect should rarely cause issues in real
 * code .
 * @ param formalType is { @ code Foo < formalType > } a supertype of { @ code Foo < T > } ?
 * @ param declaration The type variable in the context of a parameterized type . Used to infer type
 * bound when { @ code formalType } is a wildcard with implicit upper bound . */
private boolean is ( Type formalType , TypeVariable < ? > declaration ) { } }

implementation:
if ( runtimeType . equals ( formalType ) ) { return true ; } if ( formalType instanceof WildcardType ) { WildcardType your = canonicalizeWildcardType ( declaration , ( WildcardType ) formalType ) ; // if " formalType " is < ? extends Foo > , " this " can be :
// Foo , SubFoo , < ? extends Foo > , < ? extends SubFoo > , < T extends Foo > or
// < T extends SubFoo > .
// if " formalType " is < ? super Foo > , " this " can be :
// Foo , SuperFoo , < ? super Foo > or < ? super SuperFoo > .
return every ( your . getUpperBounds ( ) ) . isSupertypeOf ( runtimeType ) && every ( your . getLowerBounds ( ) ) . isSubtypeOf ( runtimeType ) ; } return canonicalizeWildcardsInType ( runtimeType ) . equals ( canonicalizeWildcardsInType ( formalType ) ) ;


signature:
public class TypeToken { /** * In reflection , { @ code Foo < ? > . getUpperBounds ( ) [ 0 ] } is always { @ code Object . class } , even when Foo
 * is defined as { @ code Foo < T extends String > } . Thus directly calling { @ code < ? > . is ( String . class ) }
 * will return false . To mitigate , we canonicalize wildcards by enforcing the following
 * invariants :
 * < ol >
 * < li > { @ code canonicalize ( t ) } always produces the equal result for equivalent types . For
 * example both { @ code Enum < ? > } and { @ code Enum < ? extends Enum < ? > > } canonicalize to { @ code
 * Enum < ? extends Enum < E > } .
 * < li > { @ code canonicalize ( t ) } produces a " literal " supertype of t . For example : { @ code Enum < ?
 * extends Enum < ? > > } canonicalizes to { @ code Enum < ? > } , which is a supertype ( if we disregard
 * the upper bound is implicitly an Enum too ) .
 * < li > If { @ code canonicalize ( A ) = = canonicalize ( B ) } , then { @ code Foo < A > . isSubtypeOf ( Foo < B > ) }
 * and vice versa . i . e . { @ code A . is ( B ) } and { @ code B . is ( A ) } .
 * < li > { @ code canonicalize ( canonicalize ( A ) ) = = canonicalize ( A ) } .
 * < / ol > */
private static Type canonicalizeTypeArg ( TypeVariable < ? > declaration , Type typeArg ) { } }

implementation: return typeArg instanceof WildcardType ? canonicalizeWildcardType ( declaration , ( ( WildcardType ) typeArg ) ) : canonicalizeWildcardsInType ( typeArg ) ;


signature:
public class TypeToken { /** * Just don ' t ever let the user access it . */
private static WildcardType canonicalizeWildcardType ( TypeVariable < ? > declaration , WildcardType type ) { } }

implementation: Type [ ] declared = declaration . getBounds ( ) ; List < Type > upperBounds = new ArrayList < > ( ) ; for ( Type bound : type . getUpperBounds ( ) ) { if ( ! any ( declared ) . isSubtypeOf ( bound ) ) { upperBounds . add ( canonicalizeWildcardsInType ( bound ) ) ; } } return new Types . WildcardTypeImpl ( type . getLowerBounds ( ) , upperBounds . toArray ( new Type [ 0 ] ) ) ;


signature:
public class TypeToken { /** * Returns the type token representing the generic type declaration of { @ code cls } . For example :
 * { @ code TypeToken . getGenericType ( Iterable . class ) } returns { @ code Iterable < T > } .
 * < p > If { @ code cls } isn ' t parameterized and isn ' t a generic array , the type token of the class is
 * returned . */
@ VisibleForTesting static < T > TypeToken < ? extends T > toGenericType ( Class < T > cls ) { } }

implementation:
if ( cls . isArray ( ) ) { Type arrayOfGenericType = Types . newArrayType ( // If we are passed with int [ ] . class , don ' t turn it to GenericArrayType
toGenericType ( cls . getComponentType ( ) ) . runtimeType ) ; @ SuppressWarnings ( "unchecked" ) // array is covariant
TypeToken < ? extends T > result = ( TypeToken < ? extends T > ) of ( arrayOfGenericType ) ; return result ; } TypeVariable < Class < T > > [ ] typeParams = cls . getTypeParameters ( ) ; Type ownerType = cls . isMemberClass ( ) && ! Modifier . isStatic ( cls . getModifiers ( ) ) ? toGenericType ( cls . getEnclosingClass ( ) ) . runtimeType : null ; if ( ( typeParams . length > 0 ) || ( ( ownerType != null ) && ownerType != cls . getEnclosingClass ( ) ) ) { @ SuppressWarnings ( "unchecked" ) // Like , it ' s Iterable < T > for Iterable . class
TypeToken < ? extends T > type = ( TypeToken < ? extends T > ) of ( Types . newParameterizedTypeWithOwner ( ownerType , cls , typeParams ) ) ; return type ; } else { return of ( cls ) ; }


signature:
public class CharStreams { /** * Copies all characters between the { @ link Readable } and { @ link Appendable } objects . Does not
 * close or flush either object .
 * @ param from the object to read from
 * @ param to the object to write to
 * @ return the number of characters copied
 * @ throws IOException if an I / O error occurs */
@ CanIgnoreReturnValue public static long copy ( Readable from , Appendable to ) throws IOException { } }

implementation:
// The most common case is that from is a Reader ( like InputStreamReader or StringReader ) so
// take advantage of that .
if ( from instanceof Reader ) { // optimize for common output types which are optimized to deal with char [ ]
if ( to instanceof StringBuilder ) { return copyReaderToBuilder ( ( Reader ) from , ( StringBuilder ) to ) ; } else { return copyReaderToWriter ( ( Reader ) from , asWriter ( to ) ) ; } } else { checkNotNull ( from ) ; checkNotNull ( to ) ; long total = 0 ; CharBuffer buf = createBuffer ( ) ; while ( from . read ( buf ) != - 1 ) { buf . flip ( ) ; to . append ( buf ) ; total += buf . remaining ( ) ; buf . clear ( ) ; } return total ; }


signature:
public class CharStreams { /** * Copies all characters between the { @ link Reader } and { @ link StringBuilder } objects . Does not
 * close or flush the reader .
 * < p > This is identical to { @ link # copy ( Readable , Appendable ) } but optimized for these specific
 * types . CharBuffer has poor performance when being written into or read out of so round tripping
 * all the bytes through the buffer takes a long time . With these specialized types we can just
 * use a char array .
 * @ param from the object to read from
 * @ param to the object to write to
 * @ return the number of characters copied
 * @ throws IOException if an I / O error occurs */
@ CanIgnoreReturnValue static long copyReaderToBuilder ( Reader from , StringBuilder to ) throws IOException { } }

implementation: checkNotNull ( from ) ; checkNotNull ( to ) ; char [ ] buf = new char [ DEFAULT_BUF_SIZE ] ; int nRead ; long total = 0 ; while ( ( nRead = from . read ( buf ) ) != - 1 ) { to . append ( buf , 0 , nRead ) ; total += nRead ; } return total ;


signature:
public class CharStreams { /** * Copies all characters between the { @ link Reader } and { @ link Writer } objects . Does not close or
 * flush the reader or writer .
 * < p > This is identical to { @ link # copy ( Readable , Appendable ) } but optimized for these specific
 * types . CharBuffer has poor performance when being written into or read out of so round tripping
 * all the bytes through the buffer takes a long time . With these specialized types we can just
 * use a char array .
 * @ param from the object to read from
 * @ param to the object to write to
 * @ return the number of characters copied
 * @ throws IOException if an I / O error occurs */
@ CanIgnoreReturnValue static long copyReaderToWriter ( Reader from , Writer to ) throws IOException { } }

implementation: checkNotNull ( from ) ; checkNotNull ( to ) ; char [ ] buf = new char [ DEFAULT_BUF_SIZE ] ; int nRead ; long total = 0 ; while ( ( nRead = from . read ( buf ) ) != - 1 ) { to . write ( buf , 0 , nRead ) ; total += nRead ; } return total ;


signature:
public class CharStreams { /** * Reads all characters from a { @ link Readable } object into a new { @ link StringBuilder } instance .
 * Does not close the { @ code Readable } .
 * @ param r the object to read from
 * @ return a { @ link StringBuilder } containing all the characters
 * @ throws IOException if an I / O error occurs */
private static StringBuilder toStringBuilder ( Readable r ) throws IOException { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; if ( r instanceof Reader ) { copyReaderToBuilder ( ( Reader ) r , sb ) ; } else { copy ( r , sb ) ; } return sb ;


signature:
public class CharStreams { /** * Discards { @ code n } characters of data from the reader . This method will block until the full
 * amount has been skipped . Does not close the reader .
 * @ param reader the reader to read from
 * @ param n the number of characters to skip
 * @ throws EOFException if this stream reaches the end before skipping all the characters
 * @ throws IOException if an I / O error occurs */
@ Beta public static void skipFully ( Reader reader , long n ) throws IOException { } }

implementation: checkNotNull ( reader ) ; while ( n > 0 ) { long amt = reader . skip ( n ) ; if ( amt == 0 ) { throw new EOFException ( ) ; } n -= amt ; }


signature:
public class CharStreams { /** * Returns a Writer that sends all output to the given { @ link Appendable } target . Closing the
 * writer will close the target if it is { @ link Closeable } , and flushing the writer will flush the
 * target if it is { @ link java . io . Flushable } .
 * @ param target the object to which output will be sent
 * @ return a new Writer object , unless target is a Writer , in which case the target is returned */
@ Beta public static Writer asWriter ( Appendable target ) { } }

implementation: if ( target instanceof Writer ) { return ( Writer ) target ; } return new AppendableWriter ( target ) ;


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: switch ( elements . length ) { case 0 : return of ( ) ; case 1 : return of ( elements [ 0 ] ) ; default : return construct ( elements . clone ( ) ) ; }


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

implementation: switch ( length ) { case 0 : return of ( ) ; case 1 : return of ( ( E ) elements [ 0 ] ) ; default : if ( length < elements . length ) { elements = Arrays . copyOf ( elements , length ) ; } return new RegularImmutableList < E > ( elements ) ; }


signature:
public class UnsignedInts { /** * Returns the least value present in { @ code array } , treating values as unsigned .
 * @ param array a < i > nonempty < / i > array of unsigned { @ code int } values
 * @ return the value present in { @ code array } that is less than or equal to every other value in
 * the array according to { @ link # compare }
 * @ throws IllegalArgumentException if { @ code array } is empty */
public static int min ( int ... array ) { } }

implementation: checkArgument ( array . length > 0 ) ; int min = flip ( array [ 0 ] ) ; for ( int i = 1 ; i < array . length ; i ++ ) { int next = flip ( array [ i ] ) ; if ( next < min ) { min = next ; } } return flip ( min ) ;


signature:
public class UnsignedInts { /** * Returns the greatest value present in { @ code array } , treating values as unsigned .
 * @ param array a < i > nonempty < / i > array of unsigned { @ code int } values
 * @ return the value present in { @ code array } that is greater than or equal to every other value
 * in the array according to { @ link # compare }
 * @ throws IllegalArgumentException if { @ code array } is empty */
public static int max ( int ... array ) { } }

implementation: checkArgument ( array . length > 0 ) ; int max = flip ( array [ 0 ] ) ; for ( int i = 1 ; i < array . length ; i ++ ) { int next = flip ( array [ i ] ) ; if ( next > max ) { max = next ; } } return flip ( max ) ;


signature:
public class UnsignedInts { /** * Sorts the array between { @ code fromIndex } inclusive and { @ code toIndex } exclusive , treating its
 * elements as unsigned 32 - bit integers .
 * @ since 23.1 */
public static void sort ( int [ ] array , int fromIndex , int toIndex ) { } }

implementation: checkNotNull ( array ) ; checkPositionIndexes ( fromIndex , toIndex , array . length ) ; for ( int i = fromIndex ; i < toIndex ; i ++ ) { array [ i ] = flip ( array [ i ] ) ; } Arrays . sort ( array , fromIndex , toIndex ) ; for ( int i = fromIndex ; i < toIndex ; i ++ ) { array [ i ] = flip ( array [ i ] ) ; }


signature:
public class UnsignedInts { /** * Sorts the elements of { @ code array } between { @ code fromIndex } inclusive and { @ code toIndex }
 * exclusive in descending order , interpreting them as unsigned 32 - bit integers .
 * @ since 23.1 */
public static void sortDescending ( int [ ] array , int fromIndex , int toIndex ) { } }

implementation: checkNotNull ( array ) ; checkPositionIndexes ( fromIndex , toIndex , array . length ) ; for ( int i = fromIndex ; i < toIndex ; i ++ ) { array [ i ] ^= Integer . MAX_VALUE ; } Arrays . sort ( array , fromIndex , toIndex ) ; for ( int i = fromIndex ; i < toIndex ; i ++ ) { array [ i ] ^= Integer . MAX_VALUE ; }


signature:
public class UnsignedInts { /** * Returns the unsigned { @ code int } value represented by a string with the given radix .
 * < p > < b > Java 8 users : < / b > use { @ link Integer # parseUnsignedInt ( String , int ) } instead .
 * @ param string the string containing the unsigned integer representation to be parsed .
 * @ param radix the radix to use while parsing { @ code s } ; must be between { @ link
 * Character # MIN _ RADIX } and { @ link Character # MAX _ RADIX } .
 * @ throws NumberFormatException if the string does not contain a valid unsigned { @ code int } , or
 * if supplied radix is invalid .
 * @ throws NullPointerException if { @ code s } is null ( in contrast to { @ link
 * Integer # parseInt ( String ) } ) */
@ CanIgnoreReturnValue public static int parseUnsignedInt ( String string , int radix ) { } }

implementation: checkNotNull ( string ) ; long result = Long . parseLong ( string , radix ) ; if ( ( result & INT_MASK ) != result ) { throw new NumberFormatException ( "Input " + string + " in base " + radix + " is not in the range of an unsigned integer" ) ; } return ( int ) result ;


signature:
public class ImmutableSortedMapFauxverideShim { /** * Not supported for ImmutableSortedMap .
 * @ throws UnsupportedOperationException always
 * @ deprecated Not supported for ImmutableSortedMap . */
@ Deprecated public static < K , V > ImmutableSortedMap . Builder < K , V > builderWithExpectedSize ( int expectedSize ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class ImmutableSortedMapFauxverideShim { /** * Not supported . < b > You are attempting to create a map that may contain a non - { @ code Comparable }
 * key . < / b > Proper calls will resolve to the version in { @ code ImmutableSortedMap } , not this dummy
 * version .
 * @ throws UnsupportedOperationException always
 * @ deprecated < b > Pass a key of type { @ code Comparable } to use { @ link
 * ImmutableSortedMap # of ( Comparable , Object ) } . < / b > */
@ Deprecated public static < K , V > ImmutableSortedMap < K , V > of ( K k1 , V v1 ) { } }


signature:
public class ImmutableMap { /** * Returns a { @ link Collector } that accumulates elements into an { @ code ImmutableMap } whose keys
 * and values are the result of applying the provided mapping functions to the input elements .
 * Entries appear in the result { @ code ImmutableMap } in encounter order .
 * < p > If the mapped keys contain duplicates ( according to { @ link Object # equals ( Object ) } , an { @ code
 * IllegalArgumentException } is thrown when the collection operation is performed . ( This differs
 * from the { @ code Collector } returned by { @ link Collectors # toMap ( Function , Function ) } , which
 * throws an { @ code IllegalStateException } . )
 * @ since 21.0 */
public static < T , K , V > Collector < T , ? , ImmutableMap < K , V > > toImmutableMap ( Function < ? super T , ? extends K > keyFunction , Function < ? super T , ? extends V > valueFunction ) { } }

implementation: return CollectCollectors . toImmutableMap ( keyFunction , valueFunction ) ;


signature:
public class ImmutableMap { /** * Returns a { @ link Collector } that accumulates elements into an { @ code ImmutableMap } whose keys
 * and values are the result of applying the provided mapping functions to the input elements .
 * < p > If the mapped keys contain duplicates ( according to { @ link Object # equals ( Object ) } ) , the
 * values are merged using the specified merging function . Entries will appear in the encounter
 * order of the first occurrence of the key .
 * @ since 21.0 */
public static < T , K , V > Collector < T , ? , ImmutableMap < K , V > > toImmutableMap ( Function < ? super T , ? extends K > keyFunction , Function < ? super T , ? extends V > valueFunction , BinaryOperator < V > mergeFunction ) { } }

implementation: checkNotNull ( keyFunction ) ; checkNotNull ( valueFunction ) ; checkNotNull ( mergeFunction ) ; return Collectors . collectingAndThen ( Collectors . toMap ( keyFunction , valueFunction , mergeFunction , LinkedHashMap :: new ) , ImmutableMap :: copyOf ) ;


signature:
public class ImmutableMap { /** * Returns the empty map . This map behaves and performs comparably to { @ link
 * Collections # emptyMap } , and is preferable mainly for consistency and maintainability of your
 * code . */
@ SuppressWarnings ( "unchecked" ) public static < K , V > ImmutableMap < K , V > of ( ) { } }

implementation: return ( ImmutableMap < K , V > ) RegularImmutableMap . EMPTY ;


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

implementation: return ImmutableBiMap . of ( k1 , v1 ) ;


signature:
public class ImmutableMap { /** * Verifies that { @ code key } and { @ code value } are non - null , and returns a new immutable entry
 * with those values .
 * < p > A call to { @ link Entry # setValue } on the returned entry will always throw { @ link
 * UnsupportedOperationException } . */
static < K , V > Entry < K , V > entryOf ( K key , V value ) { } }

implementation: checkEntryNotNull ( key , value ) ; return new AbstractMap . SimpleImmutableEntry < > ( key , value ) ;


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

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


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

implementation:
@ SuppressWarnings ( "unchecked" ) // we ' ll only be using getKey and getValue , which are covariant
Entry < K , V > [ ] entryArray = ( Entry < K , V > [ ] ) Iterables . toArray ( entries , EMPTY_ENTRY_ARRAY ) ; switch ( entryArray . length ) { case 0 : return of ( ) ; case 1 : Entry < K , V > onlyEntry = entryArray [ 0 ] ; return of ( onlyEntry . getKey ( ) , onlyEntry . getValue ( ) ) ; default : /* * The current implementation will end up using entryArray directly , though it will write
 * over the ( arbitrary , potentially mutable ) Entry objects actually stored in entryArray . */
return RegularImmutableMap . fromEntries ( entryArray ) ; }


signature:
public class ImmutableMap { /** * Guaranteed to throw an exception and leave the map unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public final V put ( K k , V v ) { } }


signature:
public class ImmutableMap { /** * Guaranteed to throw an exception and leave the map unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ Deprecated @ Override public final boolean replace ( K key , V oldValue , V newValue ) { } }


signature:
public class ImmutableMap { /** * Returns an immutable set of the mappings in this map . The iteration order is specified by the
 * method used to create this map . Typically , this is insertion order . */
@ Override public ImmutableSet < Entry < K , V > > entrySet ( ) { } }

implementation: ImmutableSet < Entry < K , V > > result = entrySet ; return ( result == null ) ? entrySet = createEntrySet ( ) : result ;


signature:
public class ImmutableMap { /** * Returns an immutable set of the keys in this map , in the same order that they appear in { @ link
 * # entrySet } . */
@ Override public ImmutableSet < K > keySet ( ) { } }

implementation: ImmutableSet < K > result = keySet ; return ( result == null ) ? keySet = createKeySet ( ) : result ;


signature:
public class ImmutableMap { /** * Returns an immutable collection of the values in this map , in the same order that they appear
 * in { @ link # entrySet } . */
@ Override public ImmutableCollection < V > values ( ) { } }

implementation: ImmutableCollection < V > result = values ; return ( result == null ) ? values = createValues ( ) : result ;


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

implementation: return new GraphBuilder < N > ( graph . isDirected ( ) ) . allowsSelfLoops ( graph . allowsSelfLoops ( ) ) . nodeOrder ( graph . nodeOrder ( ) ) ;


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

implementation: GraphBuilder < N1 > castBuilder = cast ( ) ; return new ImmutableGraph . Builder < > ( castBuilder ) ;


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

implementation: GraphBuilder < N1 > newBuilder = cast ( ) ; newBuilder . nodeOrder = checkNotNull ( nodeOrder ) ; return newBuilder ;


signature:
public class Reflection { /** * Returns the package name of { @ code classFullName } according to the Java Language Specification
 * ( section 6.7 ) . Unlike { @ link Class # getPackage } , this method only parses the class name , without
 * attempting to define the { @ link Package } and hence load files . */
public static String getPackageName ( String classFullName ) { } }

implementation: int lastDot = classFullName . lastIndexOf ( '.' ) ; return ( lastDot < 0 ) ? "" : classFullName . substring ( 0 , lastDot ) ;


signature:
public class Reflection { /** * Ensures that the given classes are initialized , as described in < a
 * href = " http : / / java . sun . com / docs / books / jls / third _ edition / html / execution . html # 12.4.2 " > JLS Section
 * 12.4.2 < / a > .
 * < p > WARNING : Normally it ' s a smell if a class needs to be explicitly initialized , because static
 * state hurts system maintainability and testability . In cases when you have no choice while
 * inter - operating with a legacy framework , this method helps to keep the code less ugly .
 * @ throws ExceptionInInitializerError if an exception is thrown during initialization of a class */
public static void initialize ( Class < ? > ... classes ) { } }

implementation: for ( Class < ? > clazz : classes ) { try { Class . forName ( clazz . getName ( ) , true , clazz . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } }


signature:
public class Reflection { /** * Returns a proxy instance that implements { @ code interfaceType } by dispatching method
 * invocations to { @ code handler } . The class loader of { @ code interfaceType } will be used to
 * define the proxy class . To implement multiple interfaces or specify a class loader , use { @ link
 * Proxy # newProxyInstance } .
 * @ throws IllegalArgumentException if { @ code interfaceType } does not specify the type of a Java
 * interface */
public static < T > T newProxy ( Class < T > interfaceType , InvocationHandler handler ) { } }

implementation: checkNotNull ( handler ) ; checkArgument ( interfaceType . isInterface ( ) , "%s is not an interface" , interfaceType ) ; Object object = Proxy . newProxyInstance ( interfaceType . getClassLoader ( ) , new Class < ? > [ ] { interfaceType } , handler ) ; return interfaceType . cast ( object ) ;


signature:
public class LineBuffer { /** * Process additional characters from the stream . When a line separator is found the contents of
 * the line and the line separator itself are passed to the abstract { @ link # handleLine } method .
 * @ param cbuf the character buffer to process
 * @ param off the offset into the buffer
 * @ param len the number of characters to process
 * @ throws IOException if an I / O error occurs
 * @ see # finish */
protected void add ( char [ ] cbuf , int off , int len ) throws IOException { } }

implementation:
int pos = off ; if ( sawReturn && len > 0 ) { // Last call to add ended with a CR ; we can handle the line now .
if ( finishLine ( cbuf [ pos ] == '\n' ) ) { pos ++ ; } } int start = pos ; for ( int end = off + len ; pos < end ; pos ++ ) { switch ( cbuf [ pos ] ) { case '\r' : line . append ( cbuf , start , pos - start ) ; sawReturn = true ; if ( pos + 1 < end ) { if ( finishLine ( cbuf [ pos + 1 ] == '\n' ) ) { pos ++ ; } } start = pos + 1 ; break ; case '\n' : line . append ( cbuf , start , pos - start ) ; finishLine ( true ) ; start = pos + 1 ; break ; default : // do nothing
} } line . append ( cbuf , start , off + len - start ) ;


signature:
public class LineBuffer { /** * Called when a line is complete . */
@ CanIgnoreReturnValue private boolean finishLine ( boolean sawNewline ) throws IOException { } }

implementation: String separator = sawReturn ? ( sawNewline ? "\r\n" : "\r" ) : ( sawNewline ? "\n" : "" ) ; handleLine ( line . toString ( ) , separator ) ; line = new StringBuilder ( ) ; sawReturn = false ; return sawNewline ;


signature:
public class Preconditions { /** * Ensures the truth of an expression involving one or more parameters to the calling method .
 * @ param expression a boolean expression
 * @ param errorMessage the exception message to use if the check fails ; will be converted to a
 * string using { @ link String # valueOf ( Object ) }
 * @ throws IllegalArgumentException if { @ code expression } is false */
public static void checkArgument ( boolean expression , @ NullableDecl Object errorMessage ) { } }

implementation: if ( ! expression ) { throw new IllegalArgumentException ( String . valueOf ( errorMessage ) ) ; }


signature:
public class Preconditions { /** * Ensures the truth of an expression involving the state of the calling instance , but not
 * involving any parameters to the calling method .
 * @ param expression a boolean expression
 * @ param errorMessage the exception message to use if the check fails ; will be converted to a
 * string using { @ link String # valueOf ( Object ) }
 * @ throws IllegalStateException if { @ code expression } is false
 * @ see Verify # verify Verify . verify ( ) */
public static void checkState ( boolean expression , @ NullableDecl Object errorMessage ) { } }

implementation: if ( ! expression ) { throw new IllegalStateException ( String . valueOf ( errorMessage ) ) ; }


signature:
public class Preconditions { /** * Ensures the truth of an expression involving the state of the calling instance , but not
 * involving any parameters to the calling method .
 * @ param expression a boolean expression
 * @ param errorMessageTemplate a template for the exception message should the check fail . The
 * message is formed by replacing each { @ code % s } placeholder in the template with an
 * argument . These are matched by position - the first { @ code % s } gets { @ code
 * errorMessageArgs [ 0 ] } , etc . Unmatched arguments will be appended to the formatted message in
 * square braces . Unmatched placeholders will be left as - is .
 * @ param errorMessageArgs the arguments to be substituted into the message template . Arguments
 * are converted to strings using { @ link String # valueOf ( Object ) } .
 * @ throws IllegalStateException if { @ code expression } is false
 * @ see Verify # verify Verify . verify ( ) */
public static void checkState ( boolean expression , @ NullableDecl String errorMessageTemplate , @ NullableDecl Object ... errorMessageArgs ) { } }

implementation: if ( ! expression ) { throw new IllegalStateException ( lenientFormat ( errorMessageTemplate , errorMessageArgs ) ) ; }


signature:
public class Preconditions { /** * Ensures the truth of an expression involving the state of the calling instance , but not
 * involving any parameters to the calling method .
 * < p > See { @ link # checkState ( boolean , String , Object . . . ) } for details .
 * @ since 20.0 ( varargs overload since 2.0) */
public static void checkState ( boolean b , @ NullableDecl String errorMessageTemplate , @ NullableDecl Object p1 , int p2 ) { } }

implementation: if ( ! b ) { throw new IllegalStateException ( lenientFormat ( errorMessageTemplate , p1 , p2 ) ) ; }


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * @ param reference an object reference
 * @ return the non - null reference that was validated
 * @ throws NullPointerException if { @ code reference } is null
 * @ see Verify # verifyNotNull Verify . verifyNotNull ( ) */
@ CanIgnoreReturnValue @ NonNullDecl public static < T extends Object > T checkNotNull ( @ NonNullDecl T reference ) { } }

implementation: if ( reference == null ) { throw new NullPointerException ( ) ; } return reference ;


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * @ param reference an object reference
 * @ param errorMessageTemplate a template for the exception message should the check fail . The
 * message is formed by replacing each { @ code % s } placeholder in the template with an
 * argument . These are matched by position - the first { @ code % s } gets { @ code
 * errorMessageArgs [ 0 ] } , etc . Unmatched arguments will be appended to the formatted message in
 * square braces . Unmatched placeholders will be left as - is .
 * @ param errorMessageArgs the arguments to be substituted into the message template . Arguments
 * are converted to strings using { @ link String # valueOf ( Object ) } .
 * @ return the non - null reference that was validated
 * @ throws NullPointerException if { @ code reference } is null
 * @ see Verify # verifyNotNull Verify . verifyNotNull ( ) */
@ CanIgnoreReturnValue @ NonNullDecl public static < T extends Object > T checkNotNull ( @ NonNullDecl T reference , @ NullableDecl String errorMessageTemplate , @ NullableDecl Object ... errorMessageArgs ) { } }

implementation: if ( reference == null ) { throw new NullPointerException ( lenientFormat ( errorMessageTemplate , errorMessageArgs ) ) ; } return reference ;


signature:
public class Preconditions { /** * Ensures that an object reference passed as a parameter to the calling method is not null .
 * < p > See { @ link # checkNotNull ( Object , String , Object . . . ) } for details .
 * @ since 20.0 ( varargs overload since 2.0) */
@ CanIgnoreReturnValue @ NonNullDecl public static < T extends Object > T checkNotNull ( @ NonNullDecl T obj , @ NullableDecl String errorMessageTemplate , char p1 ) { } }

implementation: if ( obj == null ) { throw new NullPointerException ( lenientFormat ( errorMessageTemplate , p1 ) ) ; } return obj ;


signature:
public class Preconditions { /** * Ensures that { @ code index } specifies a valid < i > position < / i > in an array , list or string of
 * size { @ code size } . A position index may range from zero to { @ code size } , inclusive .
 * @ param index a user - supplied index identifying a position in an array , list or string
 * @ param size the size of that array , list or string
 * @ param desc the text to use to describe this index in an error message
 * @ return the value of { @ code index }
 * @ throws IndexOutOfBoundsException if { @ code index } is negative or is greater than { @ code size }
 * @ throws IllegalArgumentException if { @ code size } is negative */
@ CanIgnoreReturnValue public static int checkPositionIndex ( int index , int size , @ NullableDecl String desc ) { } }

implementation:
// Carefully optimized for execution by hotspot ( explanatory comment above )
if ( index < 0 || index > size ) { throw new IndexOutOfBoundsException ( badPositionIndex ( index , size , desc ) ) ; } return index ;


signature:
public class Maps { /** * Returns an immutable map instance containing the given entries . Internally , the returned map
 * will be backed by an { @ link EnumMap } .
 * < p > The iteration order of the returned map follows the enum ' s iteration order , not the order in
 * which the elements appear in the given map .
 * @ param map the map to make an immutable copy of
 * @ return an immutable map containing those entries
 * @ since 14.0 */
@ GwtCompatible ( serializable = true ) public static < K extends Enum < K > , V > ImmutableMap < K , V > immutableEnumMap ( Map < K , ? extends V > map ) { } }

implementation:
if ( map instanceof ImmutableEnumMap ) { @ SuppressWarnings ( "unchecked" ) // safe covariant cast
ImmutableEnumMap < K , V > result = ( ImmutableEnumMap < K , V > ) map ; return result ; } Iterator < ? extends Entry < K , ? extends V > > entryItr = map . entrySet ( ) . iterator ( ) ; if ( ! entryItr . hasNext ( ) ) { return ImmutableMap . of ( ) ; } Entry < K , ? extends V > entry1 = entryItr . next ( ) ; K key1 = entry1 . getKey ( ) ; V value1 = entry1 . getValue ( ) ; checkEntryNotNull ( key1 , value1 ) ; Class < K > clazz = key1 . getDeclaringClass ( ) ; EnumMap < K , V > enumMap = new EnumMap < > ( clazz ) ; enumMap . put ( key1 , value1 ) ; while ( entryItr . hasNext ( ) ) { Entry < K , ? extends V > entry = entryItr . next ( ) ; K key = entry . getKey ( ) ; V value = entry . getValue ( ) ; checkEntryNotNull ( key , value ) ; enumMap . put ( key , value ) ; } return ImmutableEnumMap . asImmutable ( enumMap ) ;


signature:
public class Maps { /** * Creates a < i > mutable < / i > { @ code HashMap } instance with the same mappings as the specified map .
 * < p > < b > Note : < / b > if mutability is not required , use { @ link ImmutableMap # copyOf ( Map ) } instead .
 * < p > < b > Note : < / b > if { @ code K } is an { @ link Enum } type , use { @ link # newEnumMap } instead .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use the { @ code HashMap } constructor directly , taking advantage of the new
 * < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * @ param map the mappings to be placed in the new map
 * @ return a new { @ code HashMap } initialized with the mappings from { @ code map } */
public static < K , V > HashMap < K , V > newHashMap ( Map < ? extends K , ? extends V > map ) { } }

implementation: return new HashMap < > ( map ) ;


signature:
public class Maps { /** * Creates a { @ code HashMap } instance , with a high enough " initial capacity " that it < i > should < / i >
 * hold { @ code expectedSize } elements without growth . This behavior cannot be broadly guaranteed ,
 * but it is observed to be true for OpenJDK 1.7 . It also can ' t be guaranteed that the method
 * isn ' t inadvertently < i > oversizing < / i > the returned map .
 * @ param expectedSize the number of entries you expect to add to the returned map
 * @ return a new , empty { @ code HashMap } with enough capacity to hold { @ code expectedSize } entries
 * without resizing
 * @ throws IllegalArgumentException if { @ code expectedSize } is negative */
public static < K , V > HashMap < K , V > newHashMapWithExpectedSize ( int expectedSize ) { } }

implementation: return new HashMap < > ( capacity ( expectedSize ) ) ;


signature:
public class Maps { /** * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
 * larger than expectedSize and the load factor is ≥ its default ( 0.75 ) . */
static int capacity ( int expectedSize ) { } }

implementation:
if ( expectedSize < 3 ) { checkNonnegative ( expectedSize , "expectedSize" ) ; return expectedSize + 1 ; } if ( expectedSize < Ints . MAX_POWER_OF_TWO ) { // This is the calculation used in JDK8 to resize when a putAll
// happens ; it seems to be the most conservative calculation we
// can make . 0.75 is the default load factor .
return ( int ) ( ( float ) expectedSize / 0.75F + 1.0F ) ; } return Integer . MAX_VALUE ; // any large value


signature:
public class Maps { /** * Creates a < i > mutable < / i > { @ code TreeMap } instance with the same mappings as the specified map
 * and using the same ordering as the specified map .
 * < p > < b > Note : < / b > if mutability is not required , use { @ link
 * ImmutableSortedMap # copyOfSorted ( SortedMap ) } instead .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use the { @ code TreeMap } constructor directly , taking advantage of the new
 * < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * @ param map the sorted map whose mappings are to be placed in the new map and whose comparator
 * is to be used to sort the new map
 * @ return a new { @ code TreeMap } initialized with the mappings from { @ code map } and using the
 * comparator of { @ code map } */
public static < K , V > TreeMap < K , V > newTreeMap ( SortedMap < K , ? extends V > map ) { } }

implementation: return new TreeMap < > ( map ) ;


signature:
public class Maps { /** * Creates an { @ code EnumMap } instance .
 * @ param type the key type for this map
 * @ return a new , empty { @ code EnumMap } */
public static < K extends Enum < K > , V > EnumMap < K , V > newEnumMap ( Class < K > type ) { } }

implementation: return new EnumMap < > ( checkNotNull ( type ) ) ;


signature:
public class Maps { /** * Creates an { @ code EnumMap } with the same mappings as the specified map .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use the { @ code EnumMap } constructor directly , taking advantage of the new
 * < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * @ param map the map from which to initialize this { @ code EnumMap }
 * @ return a new { @ code EnumMap } initialized with the mappings from { @ code map }
 * @ throws IllegalArgumentException if { @ code m } is not an { @ code EnumMap } instance and contains
 * no mappings */
public static < K extends Enum < K > , V > EnumMap < K , V > newEnumMap ( Map < K , ? extends V > map ) { } }

implementation: return new EnumMap < > ( map ) ;


signature:
public class Maps { /** * Returns the specified comparator if not null ; otherwise returns { @ code Ordering . natural ( ) } .
 * This method is an abomination of generics ; the only purpose of this method is to contain the
 * ugly type - casting in one place . */
@ SuppressWarnings ( "unchecked" ) static < E > Comparator < ? super E > orNaturalOrder ( @ NullableDecl Comparator < ? super E > comparator ) { } }

implementation:
if ( comparator != null ) { // can ' t use ? : because of javac bug 5080917
return comparator ; } return ( Comparator < E > ) Ordering . natural ( ) ;


signature:
public class Maps { /** * Returns a live { @ link Map } view whose keys are the contents of { @ code set } and whose values are
 * computed on demand using { @ code function } . To get an immutable < i > copy < / i > instead , use { @ link
 * # toMap ( Iterable , Function ) } .
 * < p > Specifically , for each { @ code k } in the backing set , the returned map has an entry mapping
 * { @ code k } to { @ code function . apply ( k ) } . The { @ code keySet } , { @ code values } , and { @ code
 * entrySet } views of the returned map iterate in the same order as the backing set .
 * < p > Modifications to the backing set are read through to the returned map . The returned map
 * supports removal operations if the backing set does . Removal operations write through to the
 * backing set . The returned map does not support put operations .
 * < p > < b > Warning : < / b > If the function rejects { @ code null } , caution is required to make sure the
 * set does not contain { @ code null } , because the view cannot stop { @ code null } from being added
 * to the set .
 * < p > < b > Warning : < / b > This method assumes that for any instance { @ code k } of key type { @ code K } ,
 * { @ code k . equals ( k2 ) } implies that { @ code k2 } is also of type { @ code K } . Using a key type for
 * which this may not hold , such as { @ code ArrayList } , may risk a { @ code ClassCastException } when
 * calling methods on the resulting map view .
 * @ since 14.0 */
public static < K , V > Map < K , V > asMap ( Set < K > set , Function < ? super K , V > function ) { } }

implementation: return new AsMapView < > ( set , function ) ;


signature:
public class Maps { /** * Returns an immutable map whose keys are the distinct elements of { @ code keys } and whose value
 * for each key was computed by { @ code valueFunction } . The map ' s iteration order is the order of
 * the first appearance of each key in { @ code keys } .
 * < p > When there are multiple instances of a key in { @ code keys } , it is unspecified whether { @ code
 * valueFunction } will be applied to more than one instance of that key and , if it is , which
 * result will be mapped to that key in the returned map .
 * < p > If { @ code keys } is a { @ link Set } , a live view can be obtained instead of a copy using { @ link
 * Maps # asMap ( Set , Function ) } .
 * @ throws NullPointerException if any element of { @ code keys } is { @ code null } , or if { @ code
 * valueFunction } produces { @ code null } for any key
 * @ since 14.0 */
public static < K , V > ImmutableMap < K , V > toMap ( Iterable < K > keys , Function < ? super K , V > valueFunction ) { } }

implementation: return toMap ( keys . iterator ( ) , valueFunction ) ;


signature:
public class Maps { /** * Returns an immutable map whose keys are the distinct elements of { @ code keys } and whose value
 * for each key was computed by { @ code valueFunction } . The map ' s iteration order is the order of
 * the first appearance of each key in { @ code keys } .
 * < p > When there are multiple instances of a key in { @ code keys } , it is unspecified whether { @ code
 * valueFunction } will be applied to more than one instance of that key and , if it is , which
 * result will be mapped to that key in the returned map .
 * @ throws NullPointerException if any element of { @ code keys } is { @ code null } , or if { @ code
 * valueFunction } produces { @ code null } for any key
 * @ since 14.0 */
public static < K , V > ImmutableMap < K , V > toMap ( Iterator < K > keys , Function < ? super K , V > valueFunction ) { } }

implementation:
checkNotNull ( valueFunction ) ; // Using LHM instead of a builder so as not to fail on duplicate keys
Map < K , V > builder = newLinkedHashMap ( ) ; while ( keys . hasNext ( ) ) { K key = keys . next ( ) ; builder . put ( key , valueFunction . apply ( key ) ) ; } return ImmutableMap . copyOf ( builder ) ;


signature:
public class Maps { /** * Returns a map with the given { @ code values } , indexed by keys derived from those values . In
 * other words , each input value produces an entry in the map whose key is the result of applying
 * { @ code keyFunction } to that value . These entries appear in the same order as the input values .
 * Example usage :
 * < pre > { @ code
 * Color red = new Color ( " red " , 255 , 0 , 0 ) ;
 * ImmutableSet < Color > allColors = ImmutableSet . of ( red , green , blue ) ;
 * Map < String , Color > colorForName =
 * uniqueIndex ( allColors , toStringFunction ( ) ) ;
 * assertThat ( colorForName ) . containsEntry ( " red " , red ) ;
 * } < / pre >
 * < p > If your index may associate multiple values with each key , use { @ link
 * Multimaps # index ( Iterable , Function ) Multimaps . index } .
 * @ param values the values to use when constructing the { @ code Map }
 * @ param keyFunction the function used to produce the key for each value
 * @ return a map mapping the result of evaluating the function { @ code keyFunction } on each value
 * in the input collection to that value
 * @ throws IllegalArgumentException if { @ code keyFunction } produces the same key for more than one
 * value in the input collection
 * @ throws NullPointerException if any element of { @ code values } is { @ code null } , or if { @ code
 * keyFunction } produces { @ code null } for any value */
@ CanIgnoreReturnValue public static < K , V > ImmutableMap < K , V > uniqueIndex ( Iterable < V > values , Function < ? super V , K > keyFunction ) { } }

implementation:
// TODO ( lowasser ) : consider presizing the builder if values is a Collection
return uniqueIndex ( values . iterator ( ) , keyFunction ) ;


signature:
public class Maps { /** * Returns a map with the given { @ code values } , indexed by keys derived from those values . In
 * other words , each input value produces an entry in the map whose key is the result of applying
 * { @ code keyFunction } to that value . These entries appear in the same order as the input values .
 * Example usage :
 * < pre > { @ code
 * Color red = new Color ( " red " , 255 , 0 , 0 ) ;
 * Iterator < Color > allColors = ImmutableSet . of ( red , green , blue ) . iterator ( ) ;
 * Map < String , Color > colorForName =
 * uniqueIndex ( allColors , toStringFunction ( ) ) ;
 * assertThat ( colorForName ) . containsEntry ( " red " , red ) ;
 * } < / pre >
 * < p > If your index may associate multiple values with each key , use { @ link
 * Multimaps # index ( Iterator , Function ) Multimaps . index } .
 * @ param values the values to use when constructing the { @ code Map }
 * @ param keyFunction the function used to produce the key for each value
 * @ return a map mapping the result of evaluating the function { @ code keyFunction } on each value
 * in the input collection to that value
 * @ throws IllegalArgumentException if { @ code keyFunction } produces the same key for more than one
 * value in the input collection
 * @ throws NullPointerException if any element of { @ code values } is { @ code null } , or if { @ code
 * keyFunction } produces { @ code null } for any value
 * @ since 10.0 */
@ CanIgnoreReturnValue public static < K , V > ImmutableMap < K , V > uniqueIndex ( Iterator < V > values , Function < ? super V , K > keyFunction ) { } }

implementation: checkNotNull ( keyFunction ) ; ImmutableMap . Builder < K , V > builder = ImmutableMap . builder ( ) ; while ( values . hasNext ( ) ) { V value = values . next ( ) ; builder . put ( keyFunction . apply ( value ) , value ) ; } try { return builder . build ( ) ; } catch ( IllegalArgumentException duplicateKeys ) { throw new IllegalArgumentException ( duplicateKeys . getMessage ( ) + ". To index multiple values under a key, use Multimaps.index." ) ; }


signature:
public class Maps { /** * Returns an unmodifiable view of the specified set of entries . The { @ link Entry # setValue }
 * operation throws an { @ link UnsupportedOperationException } , as do any operations that would
 * modify the returned set .
 * @ param entrySet the entries for which to return an unmodifiable view
 * @ return an unmodifiable view of the entries */
static < K , V > Set < Entry < K , V > > unmodifiableEntrySet ( Set < Entry < K , V > > entrySet ) { } }

implementation: return new UnmodifiableEntrySet < > ( Collections . unmodifiableSet ( entrySet ) ) ;


signature:
public class Maps { /** * Returns an unmodifiable view of the specified map entry . The { @ link Entry # setValue } operation
 * throws an { @ link UnsupportedOperationException } . This also has the side - effect of redefining
 * { @ code equals } to comply with the Entry contract , to avoid a possible nefarious implementation
 * of equals .
 * @ param entry the entry for which to return an unmodifiable view
 * @ return an unmodifiable view of the entry */
static < K , V > Entry < K , V > unmodifiableEntry ( final Entry < ? extends K , ? extends V > entry ) { } }

implementation: checkNotNull ( entry ) ; return new AbstractMapEntry < K , V > ( ) { @ Override public K getKey ( ) { return entry . getKey ( ) ; } @ Override public V getValue ( ) { return entry . getValue ( ) ; } } ;


signature:
public class Maps { /** * Returns a synchronized ( thread - safe ) bimap backed by the specified bimap . In order to guarantee
 * serial access , it is critical that < b > all < / b > access to the backing bimap is accomplished
 * through the returned bimap .
 * < p > It is imperative that the user manually synchronize on the returned map when accessing any
 * of its collection views :
 * < pre > { @ code
 * BiMap < Long , String > map = Maps . synchronizedBiMap (
 * HashBiMap . < Long , String > create ( ) ) ;
 * Set < Long > set = map . keySet ( ) ; / / Needn ' t be in synchronized block
 * synchronized ( map ) { / / Synchronizing on map , not set !
 * Iterator < Long > it = set . iterator ( ) ; / / Must be in synchronized block
 * while ( it . hasNext ( ) ) {
 * foo ( it . next ( ) ) ;
 * } < / pre >
 * < p > Failure to follow this advice may result in non - deterministic behavior .
 * < p > The returned bimap will be serializable if the specified bimap is serializable .
 * @ param bimap the bimap to be wrapped in a synchronized view
 * @ return a synchronized view of the specified bimap */
public static < K , V > BiMap < K , V > synchronizedBiMap ( BiMap < K , V > bimap ) { } }

implementation: return Synchronized . biMap ( bimap , null ) ;


signature:
public class Maps { /** * Returns a view of a map where each value is transformed by a function . All other properties of
 * the map , such as iteration order , are left intact . For example , the code :
 * < pre > { @ code
 * Map < String , Integer > map = ImmutableMap . of ( " a " , 4 , " b " , 9 ) ;
 * Function < Integer , Double > sqrt =
 * new Function < Integer , Double > ( ) {
 * public Double apply ( Integer in ) {
 * return Math . sqrt ( ( int ) in ) ;
 * Map < String , Double > transformed = Maps . transformValues ( map , sqrt ) ;
 * System . out . println ( transformed ) ;
 * } < / pre >
 * . . . prints { @ code { a = 2.0 , b = 3.0 } } .
 * < p > Changes in the underlying map are reflected in this view . Conversely , this view supports
 * removal operations , and these are reflected in the underlying map .
 * < p > It ' s acceptable for the underlying map to contain null keys , and even null values provided
 * that the function is capable of accepting null input . The transformed map might contain null
 * values , if the function sometimes gives a null result .
 * < p > The returned map is not thread - safe or serializable , even if the underlying map is .
 * < p > The function is applied lazily , invoked when needed . This is necessary for the returned map
 * to be a view , but it means that the function will be applied many times for bulk operations
 * like { @ link Map # containsValue } and { @ code Map . toString ( ) } . For this to perform well , { @ code
 * function } should be fast . To avoid lazy evaluation when the returned map doesn ' t need to be a
 * view , copy the returned map into a new map of your choosing . */
public static < K , V1 , V2 > Map < K , V2 > transformValues ( Map < K , V1 > fromMap , Function < ? super V1 , V2 > function ) { } }

implementation: return transformEntries ( fromMap , asEntryTransformer ( function ) ) ;


signature:
public class Maps { /** * Returns a view of a navigable map where each value is transformed by a function . All other
 * properties of the map , such as iteration order , are left intact . For example , the code :
 * < pre > { @ code
 * NavigableMap < String , Integer > map = Maps . newTreeMap ( ) ;
 * map . put ( " a " , 4 ) ;
 * map . put ( " b " , 9 ) ;
 * Function < Integer , Double > sqrt =
 * new Function < Integer , Double > ( ) {
 * public Double apply ( Integer in ) {
 * return Math . sqrt ( ( int ) in ) ;
 * NavigableMap < String , Double > transformed =
 * Maps . transformNavigableValues ( map , sqrt ) ;
 * System . out . println ( transformed ) ;
 * } < / pre >
 * . . . prints { @ code { a = 2.0 , b = 3.0 } } .
 * < p > Changes in the underlying map are reflected in this view . Conversely , this view supports
 * removal operations , and these are reflected in the underlying map .
 * < p > It ' s acceptable for the underlying map to contain null keys , and even null values provided
 * that the function is capable of accepting null input . The transformed map might contain null
 * values , if the function sometimes gives a null result .
 * < p > The returned map is not thread - safe or serializable , even if the underlying map is .
 * < p > The function is applied lazily , invoked when needed . This is necessary for the returned map
 * to be a view , but it means that the function will be applied many times for bulk operations
 * like { @ link Map # containsValue } and { @ code Map . toString ( ) } . For this to perform well , { @ code
 * function } should be fast . To avoid lazy evaluation when the returned map doesn ' t need to be a
 * view , copy the returned map into a new map of your choosing .
 * @ since 13.0 */
@ GwtIncompatible // NavigableMap
public static < K , V1 , V2 > NavigableMap < K , V2 > transformValues ( NavigableMap < K , V1 > fromMap , Function < ? super V1 , V2 > function ) { } }


signature:
public class Maps { /** * Returns a view of a map whose values are derived from the original map ' s entries . In contrast
 * to { @ link # transformValues } , this method ' s entry - transformation logic may depend on the key as
 * well as the value .
 * < p > All other properties of the transformed map , such as iteration order , are left intact . For
 * example , the code :
 * < pre > { @ code
 * Map < String , Boolean > options =
 * ImmutableMap . of ( " verbose " , true , " sort " , false ) ;
 * EntryTransformer < String , Boolean , String > flagPrefixer =
 * new EntryTransformer < String , Boolean , String > ( ) {
 * public String transformEntry ( String key , Boolean value ) {
 * return value ? key : " no " + key ;
 * Map < String , String > transformed =
 * Maps . transformEntries ( options , flagPrefixer ) ;
 * System . out . println ( transformed ) ;
 * } < / pre >
 * . . . prints { @ code { verbose = verbose , sort = nosort } } .
 * < p > Changes in the underlying map are reflected in this view . Conversely , this view supports
 * removal operations , and these are reflected in the underlying map .
 * < p > It ' s acceptable for the underlying map to contain null keys and null values provided that
 * the transformer is capable of accepting null inputs . The transformed map might contain null
 * values if the transformer sometimes gives a null result .
 * < p > The returned map is not thread - safe or serializable , even if the underlying map is .
 * < p > The transformer is applied lazily , invoked when needed . This is necessary for the returned
 * map to be a view , but it means that the transformer will be applied many times for bulk
 * operations like { @ link Map # containsValue } and { @ link Object # toString } . For this to perform
 * well , { @ code transformer } should be fast . To avoid lazy evaluation when the returned map
 * doesn ' t need to be a view , copy the returned map into a new map of your choosing .
 * < p > < b > Warning : < / b > This method assumes that for any instance { @ code k } of { @ code
 * EntryTransformer } key type { @ code K } , { @ code k . equals ( k2 ) } implies that { @ code k2 } is also of
 * type { @ code K } . Using an { @ code EntryTransformer } key type for which this may not hold , such as
 * { @ code ArrayList } , may risk a { @ code ClassCastException } when calling methods on the
 * transformed map .
 * @ since 7.0 */
public static < K , V1 , V2 > Map < K , V2 > transformEntries ( Map < K , V1 > fromMap , EntryTransformer < ? super K , ? super V1 , V2 > transformer ) { } }

implementation: return new TransformedEntriesMap < > ( fromMap , transformer ) ;


signature:
public class Maps { /** * Returns a view of a sorted map whose values are derived from the original sorted map ' s entries .
 * In contrast to { @ link # transformValues } , this method ' s entry - transformation logic may depend on
 * the key as well as the value .
 * < p > All other properties of the transformed map , such as iteration order , are left intact . For
 * example , the code :
 * < pre > { @ code
 * Map < String , Boolean > options =
 * ImmutableSortedMap . of ( " verbose " , true , " sort " , false ) ;
 * EntryTransformer < String , Boolean , String > flagPrefixer =
 * new EntryTransformer < String , Boolean , String > ( ) {
 * public String transformEntry ( String key , Boolean value ) {
 * return value ? key : " yes " + key ;
 * SortedMap < String , String > transformed =
 * Maps . transformEntries ( options , flagPrefixer ) ;
 * System . out . println ( transformed ) ;
 * } < / pre >
 * . . . prints { @ code { sort = yessort , verbose = verbose } } .
 * < p > Changes in the underlying map are reflected in this view . Conversely , this view supports
 * removal operations , and these are reflected in the underlying map .
 * < p > It ' s acceptable for the underlying map to contain null keys and null values provided that
 * the transformer is capable of accepting null inputs . The transformed map might contain null
 * values if the transformer sometimes gives a null result .
 * < p > The returned map is not thread - safe or serializable , even if the underlying map is .
 * < p > The transformer is applied lazily , invoked when needed . This is necessary for the returned
 * map to be a view , but it means that the transformer will be applied many times for bulk
 * operations like { @ link Map # containsValue } and { @ link Object # toString } . For this to perform
 * well , { @ code transformer } should be fast . To avoid lazy evaluation when the returned map
 * doesn ' t need to be a view , copy the returned map into a new map of your choosing .
 * < p > < b > Warning : < / b > This method assumes that for any instance { @ code k } of { @ code
 * EntryTransformer } key type { @ code K } , { @ code k . equals ( k2 ) } implies that { @ code k2 } is also of
 * type { @ code K } . Using an { @ code EntryTransformer } key type for which this may not hold , such as
 * { @ code ArrayList } , may risk a { @ code ClassCastException } when calling methods on the
 * transformed map .
 * @ since 11.0 */
public static < K , V1 , V2 > SortedMap < K , V2 > transformEntries ( SortedMap < K , V1 > fromMap , EntryTransformer < ? super K , ? super V1 , V2 > transformer ) { } }

implementation: return new TransformedEntriesSortedMap < > ( fromMap , transformer ) ;