public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) {
    RegularImmutableSortedSet<E> elementSet =
        (RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element);
    long[] cumulativeCounts = {0, 1};
    return new RegularImmutableSortedMultiset<E>(elementSet, cumulativeCounts, 0, 1);
  }

public static < E extends Comparable < ? super E > > ImmutableSortedMultiset < E > of ( E element ) { RegularImmutableSortedSet < E > elementSet = ( RegularImmutableSortedSet < E > ) ImmutableSortedSet . of ( element ) ; long [ ] cumulativeCounts = { 0 , 1 } ; return new RegularImmutableSortedMultiset < E > ( elementSet , cumulativeCounts , 0 , 1 ) ; }

Returns an immutable sorted multiset containing a single element.

Returns an immutable sorted multiset containing a single element .


public static <E extends Comparable<?>> Builder<E> reverseOrder() {
    return new Builder<E>(Ordering.natural().reverse());
  }

public static < E extends Comparable < ? > > Builder < E > reverseOrder ( ) { return new Builder < E > ( Ordering . natural ( ) . reverse ( ) ) ; }

Returns a builder that creates immutable sorted multisets whose elements are ordered by the
reverse of their natural ordering.

Note: the type parameter {@code E} extends {@code Comparable<?>} rather than {@code
Comparable<? super E>} as a workaround for javac bug 6468354.

Returns a builder that creates immutable sorted multisets whose elements are ordered by the reverse of their natural ordering .


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

Delegate implementation which cares about the element type.

Delegate implementation which cares about the element type .


@Deprecated
  public final FluentIterable<T> preOrderTraversal(final T root) {
    checkNotNull(root);
    return new FluentIterable<T>() {
      @Override
      public UnmodifiableIterator<T> iterator() {
        return preOrderIterator(root);
      }

      @Override
      public void forEach(Consumer<? super T> action) {
        checkNotNull(action);
        new Consumer<T>() {
          @Override
          public void accept(T t) {
            action.accept(t);
            children(t).forEach(this);
          }
        }.accept(root);
      }
    };
  }

@ Deprecated public final FluentIterable < T > preOrderTraversal ( final T root ) { checkNotNull ( root ) ; return new FluentIterable < T > ( ) { @ Override public UnmodifiableIterator < T > iterator ( ) { return preOrderIterator ( root ) ; } @ Override public void forEach ( Consumer < ? super T > action ) { checkNotNull ( action ) ; new Consumer < T > ( ) { @ Override public void accept ( T t ) { action . accept ( t ) ; children ( t ) . forEach ( this ) ; } } . accept ( root ) ; } } ; }

Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order traversal.
That is, each node's subtrees are traversed after the node itself is returned.

<p>No guarantees are made about the behavior of the traversal when nodes change while iteration
is in progress or when the iterators generated by {@link #children} are advanced.

@deprecated Use {@link com.google.common.graph.Traverser#depthFirstPreOrder} instead, which has
the same behavior.

Returns an unmodifiable iterable over the nodes in a tree structure using pre - order traversal . That is each node s subtrees are traversed after the node itself is returned .


static StringBuilder newStringBuilderForCollection(int size) {
    checkNonnegative(size, "size");
    return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO));
  }

static StringBuilder newStringBuilderForCollection ( int size ) { checkNonnegative ( size , "size" ) ; return new StringBuilder ( ( int ) Math . min ( size * 8L , Ints . MAX_POWER_OF_TWO ) ) ; }

Returns best-effort-sized StringBuilder based on the given collection size.

Returns best - effort - sized StringBuilder based on the given collection size .


static TypeResolver invariantly(Type contextType) {
    Type invariantContext = WildcardCapturer.INSTANCE.capture(contextType);
    return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(invariantContext));
  }

static TypeResolver invariantly ( Type contextType ) { Type invariantContext = WildcardCapturer . INSTANCE . capture ( contextType ) ; return new TypeResolver ( ) . where ( TypeMappingIntrospector . getTypeMappings ( invariantContext ) ) ; }

Returns a resolver that resolves types "invariantly".

For example, when resolving {@code List<T>} in the context of {@code ArrayList<?>}, {@code
<T>} cannot be invariantly resolved to {@code <?>} because otherwise the parameter type of
{@code List::set} will be {@code <?>} and it'll falsely say any object can be passed into
{@code ArrayList<?>::set}.

Instead, {@code <?>} will be resolved to a capture in the form of a type variable {@code
<capture-of-? extends Object>}, effectively preventing {@code set} from accepting any type.

Returns a resolver that resolves types invariantly .


final void setMap(Map<K, Collection<V>> map) {
    this.map = map;
    totalSize = 0;
    for (Collection<V> values : map.values()) {
      checkArgument(!values.isEmpty());
      totalSize += values.size();
    }
  }

final void setMap ( Map < K , Collection < V > > map ) { this . map = map ; totalSize = 0 ; for ( Collection < V > values : map . values ( ) ) { checkArgument ( ! values . isEmpty ( ) ) ; totalSize += values . size ( ) ; } }


private void removeValuesForKey(Object key) {
    Collection<V> collection = Maps.safeRemove(map, key);

    if (collection != null) {
      int count = collection.size();
      collection.clear();
      totalSize -= count;
    }
  }

private void removeValuesForKey ( Object key ) { Collection < V > collection = Maps . safeRemove ( map , key ) ; if ( collection != null ) { int count = collection . size ( ) ; collection . clear ( ) ; totalSize -= count ; } }

Removes all values for the provided key.

Removes all values for the provided key .


private static <T> FluentIterable<T> concatNoDefensiveCopy(
      final Iterable<? extends T>... inputs) {
    for (Iterable<? extends T> input : inputs) {
      checkNotNull(input);
    }
    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return Iterators.concat(
            /* lazily generate the iterators on each input only as needed */
            new AbstractIndexedListIterator<Iterator<? extends T>>(inputs.length) {
              @Override
              public Iterator<? extends T> get(int i) {
                return inputs[i].iterator();
              }
            });
      }
    };
  }

Concatenates a varargs array of iterables without making a defensive copy of the array.

Concatenates a varargs array of iterables without making a defensive copy of the array .


@Beta
  public static <E> FluentIterable<E> of() {
    return FluentIterable.from(ImmutableList.<E>of());
  }

@ Beta public static < E > FluentIterable < E > of ( ) { return FluentIterable . from ( ImmutableList . < E > of ( ) ) ; }

Returns a fluent iterable containing no elements.

{@code Stream} equivalent: {@link Stream#empty}.

@since 20.0

Returns a fluent iterable containing no elements .


@GwtIncompatible // Array.newArray(Class, int)
  public final E[] toArray(Class<E> type) {
    return Iterables.toArray(getDelegate(), type);
  }

@
GwtIncompatible
// Array.newArray(Class, int)
public
final
E
[
]
toArray
(
Class
<
E
>
type
)
{
return
Iterables
.
toArray
(
getDelegate
(
)
,
type
)
;
}

Returns an array containing all of the elements from this fluent iterable in iteration order.

{@code Stream} equivalent: if an object array is acceptable, use {@code
stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code
stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[])
Array.newInstance(type, len))}.

@param type the type of the elements
@return a newly-allocated array into which all the elements of this fluent iterable have been
copied

Returns an array containing all of the elements from this fluent iterable in iteration order .


public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
    return ImmutableListMultimap.of(k1, v1, k2, v2);
  }

public static < K , V > ImmutableMultimap < K , V > of ( K k1 , V v1 , K k2 , V v2 ) { return ImmutableListMultimap . of ( k1 , v1 , k2 , v2 ) ; }

Returns an immutable multimap containing the given entries, in order.

Returns an immutable multimap containing the given entries in order .


@Override
  public ImmutableCollection<Entry<K, V>> entries() {
    return (ImmutableCollection<Entry<K, V>>) super.entries();
  }

@ Override public ImmutableCollection < Entry < K , V > > entries ( ) { return ( ImmutableCollection < Entry < K , V > > ) super . entries ( ) ; }

Returns an immutable collection of all key-value pairs in the multimap.

Returns an immutable collection of all key - value pairs in the multimap .


private long countBySkipping(InputStream in) throws IOException {
    long count = 0;
    long skipped;
    while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) {
      count += skipped;
    }
    return count;
  }

private long countBySkipping ( InputStream in ) throws IOException { long count = 0 ; long skipped ; while ( ( skipped = skipUpTo ( in , Integer . MAX_VALUE ) ) > 0 ) { count += skipped ; } return count ; }

Counts the bytes in the given input stream using skip if possible. Returns SKIP_FAILED if the
first call to skip threw, in which case skip may just not be supported.

Counts the bytes in the given input stream using skip if possible . Returns SKIP_FAILED if the first call to skip threw in which case skip may just not be supported .


public byte[] read() throws IOException {
    Closer closer = Closer.create();
    try {
      InputStream in = closer.register(openStream());
      Optional<Long> size = sizeIfKnown();
      return size.isPresent()
          ? ByteStreams.toByteArray(in, size.get())
          : ByteStreams.toByteArray(in);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public byte [ ] read ( ) throws IOException { Closer closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; Optional < Long > size = sizeIfKnown ( ) ; return size . isPresent ( ) ? ByteStreams . toByteArray ( in , size . get ( ) ) : ByteStreams . toByteArray ( in ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads the full contents of this byte source as a byte array.

@throws IOException if an I/O error occurs while reading from this source

Reads the full contents of this byte source as a byte array .


public HashCode hash(HashFunction hashFunction) throws IOException {
    Hasher hasher = hashFunction.newHasher();
    copyTo(Funnels.asOutputStream(hasher));
    return hasher.hash();
  }

public HashCode hash ( HashFunction hashFunction ) throws IOException { Hasher hasher = hashFunction . newHasher ( ) ; copyTo ( Funnels . asOutputStream ( hasher ) ) ; return hasher . hash ( ) ; }

Hashes the contents of this byte source using the given hash function.

@throws IOException if an I/O error occurs while reading from this source

Hashes the contents of this byte source using the given hash function .


public boolean contentEquals(ByteSource other) throws IOException {
    checkNotNull(other);

    byte[] buf1 = createBuffer();
    byte[] buf2 = createBuffer();

    Closer closer = Closer.create();
    try {
      InputStream in1 = closer.register(openStream());
      InputStream in2 = closer.register(other.openStream());
      while (true) {
        int read1 = ByteStreams.read(in1, buf1, 0, buf1.length);
        int read2 = ByteStreams.read(in2, buf2, 0, buf2.length);
        if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
          return false;
        } else if (read1 != buf1.length) {
          return true;
        }
      }
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public boolean contentEquals ( ByteSource other ) throws IOException { checkNotNull ( other ) ; byte [ ] buf1 = createBuffer ( ) ; byte [ ] buf2 = createBuffer ( ) ; Closer closer = Closer . create ( ) ; try { InputStream in1 = closer . register ( openStream ( ) ) ; InputStream in2 = closer . register ( other . openStream ( ) ) ; while ( true ) { int read1 = ByteStreams . read ( in1 , buf1 , 0 , buf1 . length ) ; int read2 = ByteStreams . read ( in2 , buf2 , 0 , buf2 . length ) ; if ( read1 != read2 || ! Arrays . equals ( buf1 , buf2 ) ) { return false ; } else if ( read1 != buf1 . length ) { return true ; } } } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Checks that the contents of this byte source are equal to the contents of the given byte
source.

@throws IOException if an I/O error occurs while reading from this source or {@code other}

Checks that the contents of this byte source are equal to the contents of the given byte source .


@SuppressWarnings("unchecked")
  public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of() {
    return (ImmutableRangeMap<K, V>) EMPTY;
  }

@ SuppressWarnings ( "unchecked" ) public static < K extends Comparable < ? > , V > ImmutableRangeMap < K , V > of ( ) { return ( ImmutableRangeMap < K , V > ) EMPTY ; }


public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of(Range<K> range, V value) {
    return new ImmutableRangeMap<>(ImmutableList.of(range), ImmutableList.of(value));
  }

public static < K extends Comparable < ? > , V > ImmutableRangeMap < K , V > of ( Range < K > range , V value ) { return new ImmutableRangeMap <> ( ImmutableList . of ( range ) , ImmutableList . of ( value ) ) ; }

Returns an immutable range map mapping a single range to a single value.

Returns an immutable range map mapping a single range to a single value .


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

Returns a hash function which computes its hash code by concatenating the hash codes of the
underlying hash functions together. This can be useful if you need to generate hash codes of a
specific length.

<p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.

@since 19.0

Returns a hash function which computes its hash code by concatenating the hash codes of the underlying hash functions together . This can be useful if you need to generate hash codes of a specific length .


public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E element) {
    return new RegularImmutableSortedSet<E>(ImmutableList.of(element), Ordering.natural());
  }

public static < E extends Comparable < ? super E > > ImmutableSortedSet < E > of ( E element ) { return new RegularImmutableSortedSet < E > ( ImmutableList . of ( element ) , Ordering . natural ( ) ) ; }

Returns an immutable sorted set containing a single element.

Returns an immutable sorted set containing a single element .


public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) {
    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
    return this;
  }

public ValueGraphBuilder < N , V > expectedNodeCount ( int expectedNodeCount ) { this . expectedNodeCount = Optional . of ( checkNonNegative ( expectedNodeCount ) ) ; return this ; }

Specifies the expected number of nodes in the graph.

@throws IllegalArgumentException if {@code expectedNodeCount} is negative

Specifies the expected number of nodes in the graph .


public static <T, S extends T> Comparator<Iterable<S>> lexicographical(Comparator<T> comparator) {
    return new LexicographicalOrdering<S>(checkNotNull(comparator));
  }

public static < T , S extends T > Comparator < Iterable < S > > lexicographical ( Comparator < T > comparator ) { return new LexicographicalOrdering < S > ( checkNotNull ( comparator ) ) ; }

think tip it over into being worthwhile.

think tip it over into being worthwhile .


public static void startFinalizer(
      Class<?> finalizableReferenceClass,
      ReferenceQueue<Object> queue,
      PhantomReference<Object> frqReference) {
    /*
     * We use FinalizableReference.class for two things:
     *
     * 1) To invoke FinalizableReference.finalizeReferent()
     *
     * 2) To detect when FinalizableReference's class loader has to be garbage collected, at which
     * point, Finalizer can stop running
     */
    if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) {
      throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + ".");
    }

    Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference);
    String threadName = Finalizer.class.getName();
    Thread thread = null;
    if (bigThreadConstructor != null) {
      try {
        boolean inheritThreadLocals = false;
        long defaultStackSize = 0;
        thread =
            bigThreadConstructor.newInstance(
                (ThreadGroup) null, finalizer, threadName, defaultStackSize, inheritThreadLocals);
      } catch (Throwable t) {
        logger.log(
            Level.INFO, "Failed to create a thread without inherited thread-local values", t);
      }
    }
    if (thread == null) {
      thread = new Thread((ThreadGroup) null, finalizer, threadName);
    }
    thread.setDaemon(true);

    try {
      if (inheritableThreadLocals != null) {
        inheritableThreadLocals.set(thread, null);
      }
    } catch (Throwable t) {
      logger.log(
          Level.INFO,
          "Failed to clear thread local values inherited by reference finalizer thread.",
          t);
    }

    thread.start();
  }

Starts the Finalizer thread. FinalizableReferenceQueue calls this method reflectively.

@param finalizableReferenceClass FinalizableReference.class.
@param queue a reference queue that the thread will poll.
@param frqReference a phantom reference to the FinalizableReferenceQueue, which will be queued
either when the FinalizableReferenceQueue is no longer referenced anywhere, or when its
close() method is called.

Starts the Finalizer thread . FinalizableReferenceQueue calls this method reflectively .


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


public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
    return of(Ordering.natural(), k1, v1);
  }

public static < K extends Comparable < ? super K > , V > ImmutableSortedMap < K , V > of ( K k1 , V v1 ) { return of ( Ordering . natural ( ) , k1 , v1 ) ; }

Returns an immutable map containing a single entry.

Returns an immutable map containing a single entry .


@SuppressWarnings("unchecked")
  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
      K k1, V v1, K k2, V v2) {
    return ofEntries(entryOf(k1, v1), entryOf(k2, v2));
  }

@ SuppressWarnings ( "unchecked" ) public static < K extends Comparable < ? super K > , V > ImmutableSortedMap < K , V > of ( K k1 , V v1 , K k2 , V v2 ) { return ofEntries ( entryOf ( k1 , v1 ) , entryOf ( k2 , v2 ) ) ; }

Returns an immutable sorted map containing the given entries, sorted by the natural ordering of
their keys.

@throws IllegalArgumentException if the two keys are equal according to their natural ordering

Returns an immutable sorted map containing the given entries sorted by the natural ordering of their keys .


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

Returns an immutable map containing the same entries as the provided sorted map, with the same
ordering.

<p>Despite the method name, this method attempts to avoid actually copying the data when it is
safe to do so. The exact circumstances under which a copy will or will not be performed are
undocumented and subject to change.

@throws NullPointerException if any key or value in {@code map} is null

Returns an immutable map containing the same entries as the provided sorted map with the same ordering .


private static void weakHashLength32WithSeeds(
      byte[] bytes, int offset, long seedA, long seedB, long[] output) {
    long part1 = load64(bytes, offset);
    long part2 = load64(bytes, offset + 8);
    long part3 = load64(bytes, offset + 16);
    long part4 = load64(bytes, offset + 24);

    seedA += part1;
    seedB = rotateRight(seedB + seedA + part4, 21);
    long c = seedA;
    seedA += part2;
    seedA += part3;
    seedB += rotateRight(seedA, 44);
    output[0] = seedA + part4;
    output[1] = seedB + c;
  }

private static void weakHashLength32WithSeeds ( byte [ ] bytes , int offset , long seedA , long seedB , long [ ] output ) { long part1 = load64 ( bytes , offset ) ; long part2 = load64 ( bytes , offset + 8 ) ; long part3 = load64 ( bytes , offset + 16 ) ; long part4 = load64 ( bytes , offset + 24 ) ; seedA += part1 ; seedB = rotateRight ( seedB + seedA + part4 , 21 ) ; long c = seedA ; seedA += part2 ; seedA += part3 ; seedB += rotateRight ( seedA , 44 ) ; output [ 0 ] = seedA + part4 ; output [ 1 ] = seedB + c ; }

Computes intermediate hash of 32 bytes of byte array from the given offset. Results are
returned in the output array because when we last measured, this was 12% faster than allocating
new arrays every time.

Computes intermediate hash of 32 bytes of byte array from the given offset . Results are returned in the output array because when we last measured this was 12% faster than allocating new arrays every time .


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

Checks that the current state is equal to the expected state.

Checks that the current state is equal to the expected state .


public static ImmutableList<Path> listFiles(Path dir) throws IOException {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
      return ImmutableList.copyOf(stream);
    } catch (DirectoryIteratorException e) {
      throw e.getCause();
    }
  }

public static ImmutableList < Path > listFiles ( Path dir ) throws IOException { try ( DirectoryStream < Path > stream = Files . newDirectoryStream ( dir ) ) { return ImmutableList . copyOf ( stream ) ; } catch ( DirectoryIteratorException e ) { throw e . getCause ( ) ; } }

Returns an immutable list of paths to the files contained in the given directory.

@throws NoSuchFileException if the file does not exist (optional specific exception)
@throws NotDirectoryException if the file could not be opened because it is not a directory
(optional specific exception)
@throws IOException if an I/O error occurs

Returns an immutable list of paths to the files contained in the given directory .


private static boolean isDirectory(
      SecureDirectoryStream<Path> dir, Path name, LinkOption... options) throws IOException {
    return dir.getFileAttributeView(name, BasicFileAttributeView.class, options)
        .readAttributes()
        .isDirectory();
  }

private static boolean isDirectory ( SecureDirectoryStream < Path > dir , Path name , LinkOption ... options ) throws IOException { return dir . getFileAttributeView ( name , BasicFileAttributeView . class , options ) . readAttributes ( ) . isDirectory ( ) ; }

Returns whether or not the file with the given name in the given dir is a directory.

Returns whether or not the file with the given name in the given dir is a directory .


public static boolean equal(Path path1, Path path2) throws IOException {
    checkNotNull(path1);
    checkNotNull(path2);
    if (Files.isSameFile(path1, path2)) {
      return true;
    }

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

Returns true if the files located by the given paths exist, are not directories, and contain
the same bytes.

@throws IOException if an I/O error occurs
@since 22.0

Returns true if the files located by the given paths exist are not directories and contain the same bytes .


@SuppressWarnings("GoodTime") // reading system time without TimeSource
  public static void touch(Path path) throws IOException {
    checkNotNull(path);

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

Like the unix command of the same name, creates an empty file or updates the last modified
timestamp of the existing file at the given path to the current system time.

Like the unix command of the same name creates an empty file or updates the last modified timestamp of the existing file at the given path to the current system time .


private static @Nullable Path getParentPath(Path path) {
    Path parent = path.getParent();

    // Paths that have a parent:
    if (parent != null) {
      // "/foo" ("/")
      // "foo/bar" ("foo")
      // "C:\foo" ("C:\")
      // "\foo" ("\" - current drive for process on Windows)
      // "C:foo" ("C:" - working dir of drive C on Windows)
      return parent;
    }

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

Returns a path to the parent directory of the given path. If the path actually has a parent
path, this is simple. Otherwise, we need to do some trickier things. Returns null if the path
is a root or is the empty path.

Returns a path to the parent directory of the given path . If the path actually has a parent path this is simple . Otherwise we need to do some trickier things . Returns null if the path is a root or is the empty path .


private static void checkAllowsInsecure(Path path, RecursiveDeleteOption[] options)
      throws InsecureRecursiveDeleteException {
    if (!Arrays.asList(options).contains(RecursiveDeleteOption.ALLOW_INSECURE)) {
      throw new InsecureRecursiveDeleteException(path.toString());
    }
  }

private static void checkAllowsInsecure ( Path path , RecursiveDeleteOption [ ] options ) throws InsecureRecursiveDeleteException { if ( ! Arrays . asList ( options ) . contains ( RecursiveDeleteOption . ALLOW_INSECURE ) ) { throw new InsecureRecursiveDeleteException ( path . toString ( ) ) ; } }

Checks that the given options allow an insecure delete, throwing an exception if not.

Checks that the given options allow an insecure delete throwing an exception if not .


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

Throws an exception indicating that one or more files couldn't be deleted. The thrown exception
contains all the exceptions in the given collection as suppressed exceptions.

Throws an exception indicating that one or more files couldn t be deleted . The thrown exception contains all the exceptions in the given collection as suppressed exceptions .


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

Applies a supplemental hash function to a given hash code, which defends against poor quality
hash functions. This is critical when the concurrent hash map uses power-of-two length hash
tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper
bits.

@param h hash code

Applies a supplemental hash function to a given hash code which defends against poor quality hash functions . This is critical when the concurrent hash map uses power - of - two length hash tables that otherwise encounter collisions for hash codes that do not differ in lower or upper bits .


Segment<K, V, E, S> segmentFor(int hash) {
    // TODO(fry): Lazily create segments?
    return segments[(hash >>> segmentShift) & segmentMask];
  }

Segment
<
K
,
V
,
E
,
S
>
segmentFor
(
int
hash
)
{
// TODO(fry): Lazily create segments?
return
segments
[
(
hash
>>>
segmentShift
)
&
segmentMask
]
;
}

Returns the segment that should be used for a key with the given hash.

@param hash the hash code for the key
@return the segment

Returns the segment that should be used for a key with the given hash .


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

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


private Range<K> coalescedRange(Range<K> range, V value) {
    Range<K> coalescedRange = range;
    Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
        entriesByLowerBound.lowerEntry(range.lowerBound);
    coalescedRange = coalesce(coalescedRange, value, lowerEntry);

    Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
        entriesByLowerBound.floorEntry(range.upperBound);
    coalescedRange = coalesce(coalescedRange, value, higherEntry);

    return coalescedRange;
  }

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

Computes the coalesced range for the given range+value - does not mutate the map.

Computes the coalesced range for the given range + value - does not mutate the map .


void unregister(Object listener) {
    Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

    for (Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
      Class<?> eventType = entry.getKey();
      Collection<Subscriber> listenerMethodsForType = entry.getValue();

      CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType);
      if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) {
        // if removeAll returns true, all we really know is that at least one subscriber was
        // removed... however, barring something very strange we can assume that if at least one
        // subscriber was removed, all subscribers on listener for that event type were... after
        // all, the definition of subscribers on a particular class is totally static
        throw new IllegalArgumentException(
            "missing event subscriber for an annotated method. Is " + listener + " registered?");
      }

      // don't try to remove the set if it's empty; that can't be done safely without a lock
      // anyway, if the set is empty it'll just be wrapping an array of length 0
    }
  }

Unregisters all subscribers on the given listener object.

Unregisters all subscribers on the given listener object .


Iterator<Subscriber> getSubscribers(Object event) {
    ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass());

    List<Iterator<Subscriber>> subscriberIterators =
        Lists.newArrayListWithCapacity(eventTypes.size());

    for (Class<?> eventType : eventTypes) {
      CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);
      if (eventSubscribers != null) {
        // eager no-copy snapshot
        subscriberIterators.add(eventSubscribers.iterator());
      }
    }

    return Iterators.concat(subscriberIterators.iterator());
  }

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

Gets an iterator representing an immutable snapshot of all subscribers to the given event at
the time this method is called.

Gets an iterator representing an immutable snapshot of all subscribers to the given event at the time this method is called .


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

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

Returns all subscribers for the given listener grouped by the type of event they subscribe to.

Returns all subscribers for the given listener grouped by the type of event they subscribe to .


public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf(
      Iterable<? extends E> elements) {
    Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]);
    checkElementsNotNull((Object[]) array);
    Arrays.sort(array);
    return asImmutableList(array);
  }

public static < E extends Comparable < ? super E > > ImmutableList < E > sortedCopyOf ( Iterable < ? extends E > elements ) { Comparable < ? > [ ] array = Iterables . toArray ( elements , new Comparable < ? > [ 0 ] ) ; checkElementsNotNull ( ( Object [ ] ) array ) ; Arrays . sort ( array ) ; return asImmutableList ( array ) ; }

Returns an immutable list containing the given elements, sorted according to their natural
order. The sorting algorithm used is stable, so elements that compare as equal will stay in the
order in which they appear in the input.

If your data has no duplicates, or you wish to deduplicate elements, use {@code
ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code
asList()} view.

Java 8 users: If you want to convert a {@link java.util.stream.Stream} to a sorted
{@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}.

@throws NullPointerException if any element in the input is null
@since 21.0

Returns an immutable list containing the given elements sorted according to their natural order . The sorting algorithm used is stable so elements that compare as equal will stay in the order in which they appear in the input .


static <E> ImmutableList<E> asImmutableList(Object[] elements) {
    return asImmutableList(elements, elements.length);
  }

static < E > ImmutableList < E > asImmutableList ( Object [ ] elements ) { return asImmutableList ( elements , elements . length ) ; }

Views the array as an immutable list. Does not check for nulls; does not copy.

<p>The array must be internally created.

Views the array as an immutable list . Does not check for nulls ; does not copy .


static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
    if (length == 0) {
      return of();
    }
    return new RegularImmutableList<E>(elements, length);
  }

static < E > ImmutableList < E > asImmutableList ( Object [ ] elements , int length ) { if ( length == 0 ) { return of ( ) ; } return new RegularImmutableList < E > ( elements , length ) ; }

Views the array as an immutable list. Does not check for nulls.

Views the array as an immutable list . Does not check for nulls .


@Beta
  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
    checkNonnegative(expectedSize, "expectedSize");
    return new ImmutableList.Builder<E>(expectedSize);
  }

@ Beta public static < E > Builder < E > builderWithExpectedSize ( int expectedSize ) { checkNonnegative ( expectedSize , "expectedSize" ) ; return new ImmutableList . Builder < E > ( expectedSize ) ; }

Returns a new builder, expecting the specified number of elements to be added.

If {@code expectedSize} is exactly the number of elements added to the builder before {@link
Builder#build} is called, the builder is likely to perform better than an unsized {@link
#builder()} would have.

It is not specified if any performance benefits apply if {@code expectedSize} is close to,
but not exactly, the number of elements added to the builder.

@since 23.1

Returns a new builder expecting the specified number of elements to be added .


@GwtIncompatible // Array.newInstance(Class, int)
  public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
    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;
  }

@
GwtIncompatible
// Array.newInstance(Class, int)
public
static
<
T
>
T
[
]
concat
(
T
[
]
first
,
T
[
]
second
,
Class
<
T
>
type
)
{
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
;
}

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

Returns a new array that contains the concatenated contents of two arrays .


static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
    int size = c.size();
    if (array.length < size) {
      array = newArray(array, size);
    }
    fillArray(c, array);
    if (array.length > size) {
      array[size] = null;
    }
    return array;
  }

static < T > T [ ] toArrayImpl ( Collection < ? > c , T [ ] array ) { int size = c . size ( ) ; if ( array . length < size ) { array = newArray ( array , size ) ; } fillArray ( c , array ) ; if ( array . length > size ) { array [ size ] = null ; } return array ; }

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.

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
only if the caller knows that the collection does not contain any null elements.

This method returns the elements in the order they are returned by the collection's
iterator.

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

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 .


@CanIgnoreReturnValue
  static Object checkElementNotNull(Object element, int index) {
    if (element == null) {
      throw new NullPointerException("at index " + index);
    }
    return element;
  }

@
CanIgnoreReturnValue
static
Object
checkElementNotNull
(
Object
element
,
int
index
)
{
if
(
element
==
)
{
throw
new
NullPointerException
(
"at index "
+
index
)
;
}
return
element
;
}


@GwtIncompatible // java.lang.reflect
  @NullableDecl
  private static Object getJLA() {
    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;
    }
  }

Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
AppEngine, and not present in non-Sun JDKs.

Returns the JavaLangAccess class that is present in all Sun JDKs . It is not allowed in AppEngine and not present in non - Sun JDKs .


private static WildcardType canonicalizeWildcardType(
      TypeVariable<?> declaration, WildcardType type) {
    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]));
  }

private static WildcardType canonicalizeWildcardType ( TypeVariable < ? > declaration , WildcardType type ) { 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 ] ) ) ; }

Just don t ever let the user access it .


static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
    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);
    }
  }

static < E > ImmutableList < E > asImmutableList ( Object [ ] elements , int length ) { 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 ) ; } }

Views the array as an immutable list. Copies if the specified range does not cover the complete
array. Does not check for nulls.

Views the array as an immutable list . Copies if the specified range does not cover the complete array . Does not check for nulls .


@Deprecated
  public static <K, V> ImmutableSortedMap.Builder<K, V> builderWithExpectedSize(int expectedSize) {
    throw new UnsupportedOperationException();
  }

@ Deprecated public static < K , V > ImmutableSortedMap . Builder < K , V > builderWithExpectedSize ( int expectedSize ) { throw new UnsupportedOperationException ( ) ; }

Not supported for ImmutableSortedMap.

@throws UnsupportedOperationException always
@deprecated Not supported for ImmutableSortedMap.


@Override
  public ImmutableSet<Entry<K, V>> entrySet() {
    ImmutableSet<Entry<K, V>> result = entrySet;
    return (result == null) ? entrySet = createEntrySet() : result;
  }

@ Override public ImmutableSet < Entry < K , V > > entrySet ( ) { ImmutableSet < Entry < K , V > > result = entrySet ; return ( result == null ) ? entrySet = createEntrySet ( ) : result ; }

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.

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 .


@CanIgnoreReturnValue
  private boolean finishLine(boolean sawNewline) throws IOException {
    String separator = sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : "");
    handleLine(line.toString(), separator);
    line = new StringBuilder();
    sawReturn = false;
    return sawNewline;
  }

@ CanIgnoreReturnValue private boolean finishLine ( boolean sawNewline ) throws IOException { String separator = sawReturn ? ( sawNewline ? "\r\n" : "\r" ) : ( sawNewline ? "\n" : "" ) ; handleLine ( line . toString ( ) , separator ) ; line = new StringBuilder ( ) ; sawReturn = false ; return sawNewline ; }


static <K, V1, V2> EntryTransformer<K, V1, V2> asEntryTransformer(
      final Function<? super V1, V2> function) {
    checkNotNull(function);
    return new EntryTransformer<K, V1, V2>() {
      @Override
      public V2 transformEntry(K key, V1 value) {
        return function.apply(value);
      }
    };
  }

static < K , V1 , V2 > EntryTransformer < K , V1 , V2 > asEntryTransformer ( final Function < ? super V1 , V2 > function ) { checkNotNull ( function ) ; return new EntryTransformer < K , V1 , V2 > ( ) { @ Override public V2 transformEntry ( K key , V1 value ) { return function . apply ( value ) ; } } ; }

Views a function as an entry transformer that ignores the entry key.

Views a function as an entry transformer that ignores the entry key .


static <V2, K, V1> Entry<K, V2> transformEntry(
      final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
    checkNotNull(transformer);
    checkNotNull(entry);
    return new AbstractMapEntry<K, V2>() {
      @Override
      public K getKey() {
        return entry.getKey();
      }

      @Override
      public V2 getValue() {
        return transformer.transformEntry(entry.getKey(), entry.getValue());
      }
    };
  }

static < V2 , K , V1 > Entry < K , V2 > transformEntry ( final EntryTransformer < ? super K , ? super V1 , V2 > transformer , final Entry < K , V1 > entry ) { checkNotNull ( transformer ) ; checkNotNull ( entry ) ; return new AbstractMapEntry < K , V2 > ( ) { @ Override public K getKey ( ) { return entry . getKey ( ) ; } @ Override public V2 getValue ( ) { return transformer . transformEntry ( entry . getKey ( ) , entry . getValue ( ) ) ; } } ; }

Returns a view of an entry transformed by the specified transformer.

Returns a view of an entry transformed by the specified transformer .


static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
      final EntryTransformer<? super K, ? super V1, V2> transformer) {
    checkNotNull(transformer);
    return new Function<Entry<K, V1>, Entry<K, V2>>() {
      @Override
      public Entry<K, V2> apply(final Entry<K, V1> entry) {
        return transformEntry(transformer, entry);
      }
    };
  }

static < K , V1 , V2 > Function < Entry < K , V1 > , Entry < K , V2 > > asEntryToEntryFunction ( final EntryTransformer < ? super K , ? super V1 , V2 > transformer ) { checkNotNull ( transformer ) ; return new Function < Entry < K , V1 > , Entry < K , V2 > > ( ) { @ Override public Entry < K , V2 > apply ( final Entry < K , V1 > entry ) { return transformEntry ( transformer , entry ) ; } } ; }

Views an entry transformer as a function from entries to entries.

Views an entry transformer as a function from entries to entries .


static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) {
    ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size());
    int i = 0;
    for (E e : list) {
      builder.put(e, i++);
    }
    return builder.build();
  }

static < E > ImmutableMap < E , Integer > indexMap ( Collection < E > list ) { ImmutableMap . Builder < E , Integer > builder = new ImmutableMap . Builder <> ( list . size ( ) ) ; int i = 0 ; for ( E e : list ) { builder . put ( e , i ++ ) ; } return builder . build ( ) ; }

Returns a map from the ith element of list to i.

Returns a map from the ith element of list to i .


protected @Nullable String pendingToString() {
    Object localValue = value;
    if (localValue instanceof SetFuture) {
      return "setFuture=[" + userObjectToString(((SetFuture) localValue).future) + "]";
    } else if (this instanceof ScheduledFuture) {
      return "remaining delay=["
          + ((ScheduledFuture) this).getDelay(TimeUnit.MILLISECONDS)
          + " ms]";
    }
    return null;
  }

protected
@
Nullable
String
pendingToString
(
)
{
Object
localValue
=
value
;
if
(
localValue
instanceof
SetFuture
)
{
return
"setFuture=["
+
userObjectToString
(
(
(
SetFuture
)
localValue
)
.
future
)
+
"]"
;
}
else
if
(
this
instanceof
ScheduledFuture
)
{
return
"remaining delay=["
+
(
(
ScheduledFuture
)
this
)
.
getDelay
(
TimeUnit
.
MILLISECONDS
)
+
" ms]"
;
}
return
;
}

Provide a human-readable explanation of why this future has not yet completed.

@return null if an explanation cannot be provided because the future is done.
@since 23.0

Provide a human - readable explanation of why this future has not yet completed .


protected void update(ByteBuffer b) {
    if (b.hasArray()) {
      update(b.array(), b.arrayOffset() + b.position(), b.remaining());
      b.position(b.limit());
    } else {
      for (int remaining = b.remaining(); remaining > 0; remaining--) {
        update(b.get());
      }
    }
  }

protected void update ( ByteBuffer b ) { if ( b . hasArray ( ) ) { update ( b . array ( ) , b . arrayOffset ( ) + b . position ( ) , b . remaining ( ) ) ; b . position ( b . limit ( ) ) ; } else { for ( int remaining = b . remaining ( ) ; remaining > 0 ; remaining -- ) { update ( b . get ( ) ) ; } } }

Updates this hasher with bytes from the given buffer.

Updates this hasher with bytes from the given buffer .


static <E> ImmutableSortedSet<E> unsafeDelegateSortedSet(
      SortedSet<E> delegate, boolean isSubset) {
    return delegate.isEmpty()
        ? emptySet(delegate.comparator())
        : new RegularImmutableSortedSet<E>(delegate, isSubset);
  }

static < E > ImmutableSortedSet < E > unsafeDelegateSortedSet ( SortedSet < E > delegate , boolean isSubset ) { return delegate . isEmpty ( ) ? emptySet ( delegate . comparator ( ) ) : new RegularImmutableSortedSet < E > ( delegate , isSubset ) ; }

Assumes that delegate doesn't have null elements and comparator.

Assumes that delegate doesn t have null elements and comparator .


@SuppressWarnings("unchecked")
  public static ImmutableSetMultimap<Object, Object> instantiate(SerializationStreamReader reader)
      throws SerializationException {
    Comparator<Object> valueComparator = (Comparator<Object>) reader.readObject();
    ImmutableSetMultimap.Builder<Object, Object> builder = ImmutableSetMultimap.builder();
    if (valueComparator != null) {
      builder.orderValuesBy(valueComparator);
    }
    return (ImmutableSetMultimap<Object, Object>)
        Multimap_CustomFieldSerializerBase.instantiate(reader, builder);
  }

@ SuppressWarnings ( "unchecked" ) public static ImmutableSetMultimap < Object , Object > instantiate ( SerializationStreamReader reader ) throws SerializationException { Comparator < Object > valueComparator = ( Comparator < Object > ) reader . readObject ( ) ; ImmutableSetMultimap . Builder < Object , Object > builder = ImmutableSetMultimap . builder ( ) ; if ( valueComparator != null ) { builder . orderValuesBy ( valueComparator ) ; } return ( ImmutableSetMultimap < Object , Object > ) Multimap_CustomFieldSerializerBase . instantiate ( reader , builder ) ; }

Serialization type safety is at the caller's mercy.

Serialization type safety is at the caller s mercy .


public long sum() {
    long sum = 0L;
    for (AtomicLong value : map.values()) {
      sum = sum + value.get();
    }
    return sum;
  }

public long sum ( ) { long sum = 0L ; for ( AtomicLong value : map . values ( ) ) { sum = sum + value . get ( ) ; } return sum ; }

Returns the sum of all values in this map.

<p>This method is not atomic: the sum may or may not include other concurrent operations.

Returns the sum of all values in this map .


private static Class<?> loadFinalizer(FinalizerLoader... loaders) {
    for (FinalizerLoader loader : loaders) {
      Class<?> finalizer = loader.loadFinalizer();
      if (finalizer != null) {
        return finalizer;
      }
    }

    throw new AssertionError();
  }

private static Class < ? > loadFinalizer ( FinalizerLoader ... loaders ) { for ( FinalizerLoader loader : loaders ) { Class < ? > finalizer = loader . loadFinalizer ( ) ; if ( finalizer != null ) { return finalizer ; } } throw new AssertionError ( ) ; }

Iterates through the given loaders until it finds one that can load Finalizer.

@return Finalizer.class

Iterates through the given loaders until it finds one that can load Finalizer .


public void dispatch() {
    // iterate by index to avoid concurrent modification exceptions
    for (int i = 0; i < listeners.size(); i++) {
      listeners.get(i).dispatch();
    }
  }

Dispatches all events enqueued prior to this call, serially and in order, for every listener.

<p>Note: this method is idempotent and safe to call from any thread

Dispatches all events enqueued prior to this call serially and in order for every listener .


public static void copy(URL from, OutputStream to) throws IOException {
    asByteSource(from).copyTo(to);
  }

public static void copy ( URL from , OutputStream to ) throws IOException { asByteSource ( from ) . copyTo ( to ) ; }

Copies all bytes from a URL to an output stream.

@param from the URL to read from
@param to the output stream
@throws IOException if an I/O error occurs

Copies all bytes from a URL to an output stream .


public void post(Object event) {
    Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event);
    if (eventSubscribers.hasNext()) {
      dispatcher.dispatch(event, eventSubscribers);
    } else if (!(event instanceof DeadEvent)) {
      // the event had no subscribers and was not itself a DeadEvent
      post(new DeadEvent(this, event));
    }
  }

Posts an event to all registered subscribers. This method will return successfully after the
event has been posted to all subscribers, and regardless of any exceptions thrown by
subscribers.

<p>If no subscribers have been subscribed for {@code event}'s class, and {@code event} is not
already a {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted.

@param event event to post.

Posts an event to all registered subscribers . This method will return successfully after the event has been posted to all subscribers and regardless of any exceptions thrown by subscribers .


@CanIgnoreReturnValue
  public MapMaker concurrencyLevel(int concurrencyLevel) {
    checkState(
        this.concurrencyLevel == UNSET_INT,
        "concurrency level was already set to %s",
        this.concurrencyLevel);
    checkArgument(concurrencyLevel > 0);
    this.concurrencyLevel = concurrencyLevel;
    return this;
  }

Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
table is internally partitioned to try to permit the indicated number of concurrent updates
without contention. Because assignment of entries to these partitions is not necessarily
uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
accommodate as many threads as will ever concurrently modify the table. Using a significantly
higher value than you need can waste space and time, and a significantly lower value can lead
to thread contention. But overestimates and underestimates within an order of magnitude do not
usually have much noticeable impact. A value of one permits only one thread to modify the map
at a time, but since read operations can proceed concurrently, this still yields higher
concurrency than full synchronization. Defaults to 4.

Note: Prior to Guava release 9.0, the default was 16. It is possible the default will
change again in the future. If you care about this value, you should always choose it
explicitly.

@throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
@throws IllegalStateException if a concurrency level was already set

Guides the allowed concurrency among update operations . Used as a hint for internal sizing . The table is internally partitioned to try to permit the indicated number of concurrent updates without contention . Because assignment of entries to these partitions is not necessarily uniform the actual concurrency observed may vary . Ideally you should choose a value to accommodate as many threads as will ever concurrently modify the table . Using a significantly higher value than you need can waste space and time and a significantly lower value can lead to thread contention . But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact . A value of one permits only one thread to modify the map at a time but since read operations can proceed concurrently this still yields higher concurrency than full synchronization . Defaults to 4 .


void setDelegates(Map<K, V> forward, Map<V, K> backward) {
    checkState(delegate == null);
    checkState(inverse == null);
    checkArgument(forward.isEmpty());
    checkArgument(backward.isEmpty());
    checkArgument(forward != backward);
    delegate = forward;
    inverse = makeInverse(backward);
  }

void setDelegates ( Map < K , V > forward , Map < V , K > backward ) { checkState ( delegate == null ) ; checkState ( inverse == null ) ; checkArgument ( forward . isEmpty ( ) ) ; checkArgument ( backward . isEmpty ( ) ) ; checkArgument ( forward != backward ) ; delegate = forward ; inverse = makeInverse ( backward ) ; }

Specifies the delegate maps going in each direction. Called by the constructor and by
subclasses during deserialization.

Specifies the delegate maps going in each direction . Called by the constructor and by subclasses during deserialization .


@GwtIncompatible // reflection
  public V[][] toArray(Class<V> valueClass) {
    @SuppressWarnings("unchecked") // TODO: safe?
    V[][] copy = (V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
    for (int i = 0; i < rowList.size(); i++) {
      System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
    }
    return copy;
  }

@
GwtIncompatible
// reflection
public
V
[
]
[
]
toArray
(
Class
<
V
>
valueClass
)
{
@
SuppressWarnings
(
"unchecked"
)
// TODO: safe?
V
[
]
[
]
copy
=
(
V
[
]
[
]
)
Array
.
newInstance
(
valueClass
,
rowList
.
size
(
)
,
columnList
.
size
(
)
)
;
for
(
int
i
=
0
;
i
<
rowList
.
size
(
)
;
i
++
)
{
System
.
arraycopy
(
array
[
i
]
,
0
,
copy
[
i
]
,
0
,
array
[
i
]
.
length
)
;
}
return
copy
;
}

Returns a two-dimensional array with the table contents. The row and column indices correspond
to the positions of the row and column in the iterables provided during table construction. If
the table lacks a mapping for a given row and column, the corresponding array element is null.

<p>Subsequent table changes will not modify the array, and vice versa.

@param valueClass class of values stored in the returned array

Returns a two - dimensional array with the table contents . The row and column indices correspond to the positions of the row and column in the iterables provided during table construction . If the table lacks a mapping for a given row and column the corresponding array element is null .


@Override
  public void execute(final Runnable task) {
    checkNotNull(task);
    final Runnable submittedTask;
    final long oldRunCount;
    synchronized (queue) {
      // If the worker is already running (or execute() on the delegate returned successfully, and
      // the worker has yet to start) then we don't need to start the worker.
      if (workerRunningState == RUNNING || workerRunningState == QUEUED) {
        queue.add(task);
        return;
      }

      oldRunCount = workerRunCount;

      // If the worker is not yet running, the delegate Executor might reject our attempt to start
      // it. To preserve FIFO order and failure atomicity of rejected execution when the same
      // Runnable is executed more than once, allocate a wrapper that we know is safe to remove by
      // object identity.
      // A data structure that returned a removal handle from add() would allow eliminating this
      // allocation.
      submittedTask =
          new Runnable() {
            @Override
            public void run() {
              task.run();
            }
          };
      queue.add(submittedTask);
      workerRunningState = QUEUING;
    }

    try {
      executor.execute(worker);
    } catch (RuntimeException | Error t) {
      synchronized (queue) {
        boolean removed =
            (workerRunningState == IDLE || workerRunningState == QUEUING)
                && queue.removeLastOccurrence(submittedTask);
        // If the delegate is directExecutor(), the submitted runnable could have thrown a REE. But
        // that's handled by the log check that catches RuntimeExceptions in the queue worker.
        if (!(t instanceof RejectedExecutionException) || removed) {
          throw t;
        }
      }
      return;
    }

    /*
     * This is an unsynchronized read! After the read, the function returns immediately or acquires
     * the lock to check again. Since an IDLE state was observed inside the preceding synchronized
     * block, and reference field assignment is atomic, this may save reacquiring the lock when
     * another thread or the worker task has cleared the count and set the state.
     *
     * <p>When {@link #executor} is a directExecutor(), the value written to
     * {@code workerRunningState} will be available synchronously, and behaviour will be
     * deterministic.
     */
    @SuppressWarnings("GuardedBy")
    boolean alreadyMarkedQueued = workerRunningState != QUEUING;
    if (alreadyMarkedQueued) {
      return;
    }
    synchronized (queue) {
      if (workerRunCount == oldRunCount && workerRunningState == QUEUING) {
        workerRunningState = QUEUED;
      }
    }
  }

Adds a task to the queue and makes sure a worker thread is running.

<p>If this method throws, e.g. a {@code RejectedExecutionException} from the delegate executor,
execution of tasks will stop until a call to this method or to {@link #resume()} is made.

Adds a task to the queue and makes sure a worker thread is running .


@Beta
  public static <R, C, V1, V2> Table<R, C, V2> transformValues(
      Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
    return new TransformedTable<>(fromTable, function);
  }

@ Beta public static < R , C , V1 , V2 > Table < R , C , V2 > transformValues ( Table < R , C , V1 > fromTable , Function < ? super V1 , V2 > function ) { return new TransformedTable <> ( fromTable , function ) ; }

Returns a view of a table where each value is transformed by a function. All other properties
of the table, such as iteration order, are left intact.

Changes in the underlying table are reflected in this view. Conversely, this view supports
removal operations, and these are reflected in the underlying table.

It's acceptable for the underlying table to contain null keys, and even null values provided
that the function is capable of accepting null input. The transformed table might contain null
values, if the function sometimes gives a null result.

The returned table is not thread-safe or serializable, even if the underlying table is.

The function is applied lazily, invoked when needed. This is necessary for the returned
table to be a view, but it means that the function will be applied many times for bulk
operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform
well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't
need to be a view, copy the returned table into a new table of your choosing.

@since 10.0

Returns a view of a table where each value is transformed by a function . All other properties of the table such as iteration order are left intact .


public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) {
    TreeMultiset<E> multiset = create();
    Iterables.addAll(multiset, elements);
    return multiset;
  }

public static < E extends Comparable > TreeMultiset < E > create ( Iterable < ? extends E > elements ) { TreeMultiset < E > multiset = create ( ) ; Iterables . addAll ( multiset , elements ) ; return multiset ; }

Creates an empty multiset containing the given initial elements, sorted according to the
elements' natural order.

This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.

The type specification is {@code <E extends Comparable>}, instead of the more specific
{@code <E extends Comparable<? super E>>}, to support classes defined without generics.

Creates an empty multiset containing the given initial elements sorted according to the elements natural order .


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

Adds the chain to the seen set, and returns whether all the chain was new to us.

Adds the chain to the seen set and returns whether all the chain was new to us .


@J2ObjCIncompatible
  @GwtIncompatible // java.time.Duration
  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
  public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) {
    return expireAfterWrite(duration.toNanos(), TimeUnit.NANOSECONDS);
  }

@
J2ObjCIncompatible
@
GwtIncompatible
// java.time.Duration
@
SuppressWarnings
(
"GoodTime"
)
// java.time.Duration decomposition
public
CacheBuilder
<
K
,
V
>
expireAfterWrite
(
java
.
time
.
Duration
duration
)
{
return
expireAfterWrite
(
duration
.
toNanos
(
)
,
TimeUnit
.
NANOSECONDS
)
;
}

Specifies that each entry should be automatically removed from the cache once a fixed duration
has elapsed after the entry's creation, or the most recent replacement of its value.

When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
useful in testing, or to disable caching temporarily without a code change.

Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
write operations. Expired entries are cleaned up as part of the routine maintenance described
in the class javadoc.

@param duration the length of time after an entry is created that it should be automatically
removed
@return this {@code CacheBuilder} instance (for chaining)
@throws IllegalArgumentException if {@code duration} is negative
@throws IllegalStateException if the time to live or time to idle was already set
@throws ArithmeticException for durations greater than +/- approximately 292 years
@since 25.0

Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry s creation or the most recent replacement of its value .


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

Sets the priority for new threads created with this ThreadFactory.

@param priority the priority for new Threads created with this ThreadFactory
@return this for the builder pattern

Sets the priority for new threads created with this ThreadFactory .


public static HostAndPort fromParts(String host, int port) {
    checkArgument(isValidPort(port), "Port out of range: %s", port);
    HostAndPort parsedHost = fromString(host);
    checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host);
    return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons);
  }

public
static
HostAndPort
fromParts
(
String
host
,
int
port
)
{
checkArgument
(
isValidPort
(
port
)
,
"Port out of range: %s"
,
port
)
;
HostAndPort
parsedHost
=
fromString
(
host
)
;
checkArgument
(
!
parsedHost
.
hasPort
(
)
,
"Host has a port: %s"
,
host
)
;
return
new
HostAndPort
(
parsedHost
.
host
,
port
,
parsedHost
.
hasBracketlessColons
)
;
}

Build a HostAndPort instance from separate host and port values.

<p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to
prohibit these.

@param host the host string to parse. Must not contain a port number.
@param port a port number from [0..65535]
@return if parsing was successful, a populated HostAndPort object.
@throws IllegalArgumentException if {@code host} contains a port number, or {@code port} is out
of range.

Build a HostAndPort instance from separate host and port values .


public static HostAndPort fromHost(String host) {
    HostAndPort parsedHost = fromString(host);
    checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host);
    return parsedHost;
  }

public
static
HostAndPort
fromHost
(
String
host
)
{
HostAndPort
parsedHost
=
fromString
(
host
)
;
checkArgument
(
!
parsedHost
.
hasPort
(
)
,
"Host has a port: %s"
,
host
)
;
return
parsedHost
;
}

Build a HostAndPort instance from a host only.

<p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to
prohibit these.

@param host the host-only string to parse. Must not contain a port number.
@return if parsing was successful, a populated HostAndPort object.
@throws IllegalArgumentException if {@code host} contains a port number.
@since 17.0

Build a HostAndPort instance from a host only .


public static HostAndPort fromString(String hostPortString) {
    checkNotNull(hostPortString);
    String host;
    String portString = null;
    boolean hasBracketlessColons = false;

    if (hostPortString.startsWith("[")) {
      String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString);
      host = hostAndPort[0];
      portString = hostAndPort[1];
    } else {
      int colonPos = hostPortString.indexOf(':');
      if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
        // Exactly 1 colon. Split into host:port.
        host = hostPortString.substring(0, colonPos);
        portString = hostPortString.substring(colonPos + 1);
      } else {
        // 0 or 2+ colons. Bare hostname or IPv6 literal.
        host = hostPortString;
        hasBracketlessColons = (colonPos >= 0);
      }
    }

    int port = NO_PORT;
    if (!Strings.isNullOrEmpty(portString)) {
      // Try to parse the whole port string as a number.
      // JDK7 accepts leading plus signs. We don't want to.
      checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString);
      try {
        port = Integer.parseInt(portString);
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
      }
      checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString);
    }

    return new HostAndPort(host, port, hasBracketlessColons);
  }

Split a freeform string into a host and port, without strict validation.

<p>Note that the host-only formats will leave the port field undefined. You can use {@link
#withDefaultPort(int)} to patch in a default value.

@param hostPortString the input string to parse.
@return if parsing was successful, a populated HostAndPort object.
@throws IllegalArgumentException if nothing meaningful could be parsed.

Split a freeform string into a host and port without strict validation .


private static String[] getHostAndPortFromBracketedHost(String hostPortString) {
    int colonIndex = 0;
    int closeBracketIndex = 0;
    checkArgument(
        hostPortString.charAt(0) == '[',
        "Bracketed host-port string must start with a bracket: %s",
        hostPortString);
    colonIndex = hostPortString.indexOf(':');
    closeBracketIndex = hostPortString.lastIndexOf(']');
    checkArgument(
        colonIndex > -1 && closeBracketIndex > colonIndex,
        "Invalid bracketed host/port: %s",
        hostPortString);

    String host = hostPortString.substring(1, closeBracketIndex);
    if (closeBracketIndex + 1 == hostPortString.length()) {
      return new String[] {host, ""};
    } else {
      checkArgument(
          hostPortString.charAt(closeBracketIndex + 1) == ':',
          "Only a colon may follow a close bracket: %s",
          hostPortString);
      for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) {
        checkArgument(
            Character.isDigit(hostPortString.charAt(i)),
            "Port must be numeric: %s",
            hostPortString);
      }
      return new String[] {host, hostPortString.substring(closeBracketIndex + 2)};
    }
  }

Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.

@param hostPortString the full bracketed host-port specification. Post might not be specified.
@return an array with 2 strings: host and port, in that order.
@throws IllegalArgumentException if parsing the bracketed host-port string fails.

Parses a bracketed host - port string throwing IllegalArgumentException if parsing fails .


static <T> GeneralRange<T> all(Comparator<? super T> comparator) {
    return new GeneralRange<T>(comparator, false, null, OPEN, false, null, OPEN);
  }

static < T > GeneralRange < T > all ( Comparator < ? super T > comparator ) { return new GeneralRange < T > ( comparator , false , null , OPEN , false , null , OPEN ) ; }

Returns the whole range relative to the specified comparator.

Returns the whole range relative to the specified comparator .


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

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

Returns the same range relative to the reversed comparator.

Returns the same range relative to the reversed comparator .


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

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

the elements are known to be non - null .


public static <B> ImmutableTypeToInstanceMap<B> of() {
    return new ImmutableTypeToInstanceMap<B>(ImmutableMap.<TypeToken<? extends B>, B>of());
  }

public static < B > ImmutableTypeToInstanceMap < B > of ( ) { return new ImmutableTypeToInstanceMap < B > ( ImmutableMap . < TypeToken < ? extends B > , B > of ( ) ) ; }


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

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

CycleDetectingLock implementations must call this method before attempting to acquire the lock.

CycleDetectingLock implementations must call this method before attempting to acquire the lock .


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

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

Returns a view of the intersection of this range set with the given range.

Returns a view of the intersection of this range set with the given range .


static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) {
    boolean reusable =
        entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable();
    return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value);
  }

static < K , V > ImmutableMapEntry < K , V > makeImmutable ( Entry < K , V > entry , K key , V value ) { boolean reusable = entry instanceof ImmutableMapEntry && ( ( ImmutableMapEntry < K , V > ) entry ) . isReusable ( ) ; return reusable ? ( ImmutableMapEntry < K , V > ) entry : new ImmutableMapEntry < K , V > ( key , value ) ; }

Makes an entry usable internally by a new ImmutableMap without rereading its contents.

Makes an entry usable internally by a new ImmutableMap without rereading its contents .


static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) {
    return makeImmutable(entry, entry.getKey(), entry.getValue());
  }

static < K , V > ImmutableMapEntry < K , V > makeImmutable ( Entry < K , V > entry ) { return makeImmutable ( entry , entry . getKey ( ) , entry . getValue ( ) ) ; }

Makes an entry usable internally by a new ImmutableMap.

Makes an entry usable internally by a new ImmutableMap .


private static UnicodeEscaper wrap(final CharEscaper escaper) {
    return new UnicodeEscaper() {
      @Override
      protected char[] escape(int cp) {
        // If a code point maps to a single character, just escape that.
        if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
          return escaper.escape((char) cp);
        }
        // Convert the code point to a surrogate pair and escape them both.
        // Note: This code path is horribly slow and typically allocates 4 new
        // char[] each time it is invoked. However this avoids any
        // synchronization issues and makes the escaper thread safe.
        char[] surrogateChars = new char[2];
        Character.toChars(cp, surrogateChars, 0);
        char[] hiChars = escaper.escape(surrogateChars[0]);
        char[] loChars = escaper.escape(surrogateChars[1]);

        // If either hiChars or lowChars are non-null, the CharEscaper is trying
        // to escape the characters of a surrogate pair separately. This is
        // uncommon and applies only to escapers that assume UCS-2 rather than
        // UTF-16. See: http://en.wikipedia.org/wiki/UTF-16/UCS-2
        if (hiChars == null && loChars == null) {
          // We expect this to be the common code path for most escapers.
          return null;
        }
        // Combine the characters and/or escaped sequences into a single array.
        int hiCount = hiChars != null ? hiChars.length : 1;
        int loCount = loChars != null ? loChars.length : 1;
        char[] output = new char[hiCount + loCount];
        if (hiChars != null) {
          // TODO: Is this faster than System.arraycopy() for small arrays?
          for (int n = 0; n < hiChars.length; ++n) {
            output[n] = hiChars[n];
          }
        } else {
          output[0] = surrogateChars[0];
        }
        if (loChars != null) {
          for (int n = 0; n < loChars.length; ++n) {
            output[hiCount + n] = loChars[n];
          }
        } else {
          output[hiCount] = surrogateChars[1];
        }
        return output;
      }
    };
  }

Private helper to wrap a CharEscaper as a UnicodeEscaper.

Private helper to wrap a CharEscaper as a UnicodeEscaper .


public void add(double x, double y) {
    // We extend the recursive expression for the one-variable case at Art of Computer Programming
    // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i.
    // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i.
    // We also define the sum of the products of the differences from the means
    //           C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n
    // for all n >= 1. Then for all n > 1:
    //       C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1}
    // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1}
    //               = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1}
    //               = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1}
    //               = (x_n - X_n) (y_n - Y_{n-1})
    xStats.add(x);
    if (isFinite(x) && isFinite(y)) {
      if (xStats.count() > 1) {
        sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean());
      }
    } else {
      sumOfProductsOfDeltas = NaN;
    }
    yStats.add(y);
  }

Adds the given pair of values to the dataset.

Adds the given pair of values to the dataset .


public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
    checkEntryNotNull(k1, v1);
    return new RegularImmutableBiMap<>(new Object[] {k1, v1}, 1);
  }

public static < K , V > ImmutableBiMap < K , V > of ( K k1 , V v1 ) { checkEntryNotNull ( k1 , v1 ) ; return new RegularImmutableBiMap <> ( new Object [ ] { k1 , v1 } , 1 ) ; }

Returns an immutable bimap containing a single entry.

Returns an immutable bimap containing a single entry .


@Beta
  public static <K, V> ImmutableBiMap<K, V> copyOf(
      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
    int estimatedSize =
        (entries instanceof Collection)
            ? ((Collection<?>) entries).size()
            : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY;
    return new Builder<K, V>(estimatedSize).putAll(entries).build();
  }

@ Beta public static < K , V > ImmutableBiMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { int estimatedSize = ( entries instanceof Collection ) ? ( ( Collection < ? > ) entries ) . size ( ) : ImmutableCollection . Builder . DEFAULT_INITIAL_CAPACITY ; return new Builder < K , V > ( estimatedSize ) . putAll ( entries ) . build ( ) ; }

Returns an immutable bimap containing the given entries. The returned bimap iterates over
entries in the same order as the original iterable.

@throws IllegalArgumentException if two keys have the same value or two values have the same
key
@throws NullPointerException if any key, value, or entry is null
@since 19.0

Returns an immutable bimap containing the given entries . The returned bimap iterates over entries in the same order as the original iterable .


@SuppressWarnings("unchecked")
  public static <E> Function<E, E> identity() {
    return (Function<E, E>) IdentityFunction.INSTANCE;
  }

@ SuppressWarnings ( "unchecked" ) public static < E > Function < E , E > identity ( ) { return ( Function < E , E > ) IdentityFunction . INSTANCE ; }

implementation is "fully variant"; E has become a "pass-through" type

implementation is fully variant ; E has become a pass - through type


public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
    return new PredicateFunction<T>(predicate);
  }

public static < T > Function < T , Boolean > forPredicate ( Predicate < T > predicate ) { return new PredicateFunction < T > ( predicate ) ; }

Creates a function that returns the same boolean output as the given predicate for all inputs.

The returned function is consistent with equals (as documented at {@link
Function#apply}) if and only if {@code predicate} is itself consistent with equals.

Java 8 users: use the method reference {@code predicate::test} instead.

Creates a function that returns the same boolean output as the given predicate for all inputs .


@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
  static <K, V> ValueReference<K, V> unset() {
    return (ValueReference<K, V>) UNSET;
  }

Singleton placeholder that indicates a value is being loaded.

Singleton placeholder that indicates a value is being loaded .


boolean isExpired(ReferenceEntry<K, V> entry, long now) {
    checkNotNull(entry);
    if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
      return true;
    }
    if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
      return true;
    }
    return false;
  }

boolean isExpired ( ReferenceEntry < K , V > entry , long now ) { checkNotNull ( entry ) ; if ( expiresAfterAccess ( ) && ( now - entry . getAccessTime ( ) >= expireAfterAccessNanos ) ) { return true ; } if ( expiresAfterWrite ( ) && ( now - entry . getWriteTime ( ) >= expireAfterWriteNanos ) ) { return true ; } return false ; }


final long reserveAndGetWaitLength(int permits, long nowMicros) {
    long momentAvailable = reserveEarliestAvailable(permits, nowMicros);
    return max(momentAvailable - nowMicros, 0);
  }

final long reserveAndGetWaitLength ( int permits , long nowMicros ) { long momentAvailable = reserveEarliestAvailable ( permits , nowMicros ) ; return max ( momentAvailable - nowMicros , 0 ) ; }

Reserves next ticket and returns the wait time that the caller must wait for.

@return the required wait time, never negative

Reserves next ticket and returns the wait time that the caller must wait for .


protected static int codePointAt(CharSequence seq, int index, int end) {
    checkNotNull(seq);
    if (index < end) {
      char c1 = seq.charAt(index++);
      if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) {
        // Fast path (first test is probably all we need to do)
        return c1;
      } else if (c1 <= Character.MAX_HIGH_SURROGATE) {
        // If the high surrogate was the last character, return its inverse
        if (index == end) {
          return -c1;
        }
        // Otherwise look for the low surrogate following it
        char c2 = seq.charAt(index);
        if (Character.isLowSurrogate(c2)) {
          return Character.toCodePoint(c1, c2);
        }
        throw new IllegalArgumentException(
            "Expected low surrogate but got char '"
                + c2
                + "' with value "
                + (int) c2
                + " at index "
                + index
                + " in '"
                + seq
                + "'");
      } else {
        throw new IllegalArgumentException(
            "Unexpected low surrogate character '"
                + c1
                + "' with value "
                + (int) c1
                + " at index "
                + (index - 1)
                + " in '"
                + seq
                + "'");
      }
    }
    throw new IndexOutOfBoundsException("Index exceeds specified range");
  }

Returns the Unicode code point of the character at the given index.

Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)}
this method will never fail silently when encountering an invalid surrogate pair.

The behaviour of this method is as follows:

If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.

If the character at the specified index is not a surrogate, it is returned.

If the first character was a high surrogate value, then an attempt is made to read the
next character.

If the end of the sequence was reached, the negated value of the trailing high
surrogate is returned.

If the next character was a valid low surrogate, the code point value of the
high/low surrogate pair is returned.

If the next character was not a low surrogate value, then {@link
IllegalArgumentException} is thrown.

If the first character was a low surrogate value, {@link IllegalArgumentException} is
thrown.

@param seq the sequence of characters from which to decode the code point
@param index the index of the first character to decode
@param end the index beyond the last valid character to decode
@return the Unicode code point for the given index or the negated value of the trailing high
surrogate character at the end of the sequence

Returns the Unicode code point of the character at the given index .


private void ensureCapacity(int minCapacity) {
    if (nextInBucketKToV.length < minCapacity) {
      int oldCapacity = nextInBucketKToV.length;
      int newCapacity = ImmutableCollection.Builder.expandedCapacity(oldCapacity, minCapacity);

      keys = Arrays.copyOf(keys, newCapacity);
      values = Arrays.copyOf(values, newCapacity);
      nextInBucketKToV = expandAndFillWithAbsent(nextInBucketKToV, newCapacity);
      nextInBucketVToK = expandAndFillWithAbsent(nextInBucketVToK, newCapacity);
      prevInInsertionOrder = expandAndFillWithAbsent(prevInInsertionOrder, newCapacity);
      nextInInsertionOrder = expandAndFillWithAbsent(nextInInsertionOrder, newCapacity);
    }

    if (hashTableKToV.length < minCapacity) {
      int newTableSize = Hashing.closedTableSize(minCapacity, 1.0);
      hashTableKToV = createFilledWithAbsent(newTableSize);
      hashTableVToK = createFilledWithAbsent(newTableSize);

      for (int entryToRehash = 0; entryToRehash < size; entryToRehash++) {
        int keyHash = Hashing.smearedHash(keys[entryToRehash]);
        int keyBucket = bucket(keyHash);
        nextInBucketKToV[entryToRehash] = hashTableKToV[keyBucket];
        hashTableKToV[keyBucket] = entryToRehash;

        int valueHash = Hashing.smearedHash(values[entryToRehash]);
        int valueBucket = bucket(valueHash);
        nextInBucketVToK[entryToRehash] = hashTableVToK[valueBucket];
        hashTableVToK[valueBucket] = entryToRehash;
      }
    }
  }

private void ensureCapacity ( int minCapacity ) { if ( nextInBucketKToV . length < minCapacity ) { int oldCapacity = nextInBucketKToV . length ; int newCapacity = ImmutableCollection . Builder . expandedCapacity ( oldCapacity , minCapacity ) ; keys = Arrays . copyOf ( keys , newCapacity ) ; values = Arrays . copyOf ( values , newCapacity ) ; nextInBucketKToV = expandAndFillWithAbsent ( nextInBucketKToV , newCapacity ) ; nextInBucketVToK = expandAndFillWithAbsent ( nextInBucketVToK , newCapacity ) ; prevInInsertionOrder = expandAndFillWithAbsent ( prevInInsertionOrder , newCapacity ) ; nextInInsertionOrder = expandAndFillWithAbsent ( nextInInsertionOrder , newCapacity ) ; } if ( hashTableKToV . length < minCapacity ) { int newTableSize = Hashing . closedTableSize ( minCapacity , 1.0 ) ; hashTableKToV = createFilledWithAbsent ( newTableSize ) ; hashTableVToK = createFilledWithAbsent ( newTableSize ) ; for ( int entryToRehash = 0 ; entryToRehash < size ; entryToRehash ++ ) { int keyHash = Hashing . smearedHash ( keys [ entryToRehash ] ) ; int keyBucket = bucket ( keyHash ) ; nextInBucketKToV [ entryToRehash ] = hashTableKToV [ keyBucket ] ; hashTableKToV [ keyBucket ] = entryToRehash ; int valueHash = Hashing . smearedHash ( values [ entryToRehash ] ) ; int valueBucket = bucket ( valueHash ) ; nextInBucketVToK [ entryToRehash ] = hashTableVToK [ valueBucket ] ; hashTableVToK [ valueBucket ] = entryToRehash ; } } }

Ensures that all of the internal structures in the HashBiMap are ready for this many elements.

Ensures that all of the internal structures in the HashBiMap are ready for this many elements .