ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Guava: Google Core Libraries for Java

2019-03-04 14:49:46  阅读:388  来源: 互联网

标签:ImmutableSet Core use collection Libraries copyOf Guava example


Guava is a set of core libraries that includes new collection types (such as multimap and multiset), immutable collections, a graph library, functional types, an in-memory cache, and APIs/utilities for concurrency, I/O, hashing, primitives, reflection, string processing, and much more!

Guava comes in two flavors.

  • The JRE flavor requires JDK 1.8 or higher.
  • If you need support for JDK 1.7 or Android, use the Android flavor. You can find the Android Guava source in the androiddirectory.

Adding Guava to your build

Guava's Maven group ID is com.google.guava and its artifact ID is guava. Guava provides two different "flavors": one for use on a (Java 8+) JRE and one for use on Android or Java 7 or by any library that wants to be compatible with either of those. These flavors are specified in the Maven version field as either 27.0.1-jre or 27.0.1-android. For more about depending on Guava, see using Guava in your build.

To add a dependency on Guava using Maven, use the following:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>27.0.1-jre</version>
  <!-- or, for Android: -->
  <version>27.0.1-android</version>
</dependency>

To add a dependency using Gradle:

dependencies {
  compile 'com.google.guava:guava:27.0.1-jre'
  // or, for Android:
  api 'com.google.guava:guava:27.0.1-android'
}


Immutable Collections


Example



public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "purple");

class Foo {
  final ImmutableSet<Bar> bars;
  Foo(Set<Bar> bars) {
    this.bars = ImmutableSet.copyOf(bars); // defensive copy!
  }
}

Why?


Immutable objects have many advantages, including:


  • Safe for use by untrusted libraries.
  • Thread-safe: can be used by many threads with no risk of race conditions.
  • Doesn't need to support mutation, and can make time and space savings with that assumption. All immutable collection implementations are more memory-efficient than their mutable siblings. (analysis)
  • Can be used as a constant, with the expectation that it will remain fixed.

Making immutable copies of objects is a good defensive programming technique. Guava provides simple, easy-to-use immutable versions of each standard Collection type, including Guava's own Collection variations.


The JDK provides Collections.unmodifiableXXX methods, but in our opinion, these can be


  • unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies
  • unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection
  • inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

When you don't expect to modify a collection, or expect a collection to remain constant, it's a good practice to defensively copy it into an immutable collection.


Important: Each of the Guava immutable collection implementations rejects null values. We did an exhaustive study on Google's internal code base that indicated that null elements were allowed in collections about 5% of the time, and the other 95% of cases were best served by failing fast on nulls. If you need to use null values, consider using Collections.unmodifiableList and its friends on a collection implementation that permits null. More detailed suggestions can be found here.


How?


An ImmutableXXX collection can be created in several ways:


  • using the copyOf method, for example, ImmutableSet.copyOf(set)
  • using the of method, for example, ImmutableSet.of("a", "b", "c") or ImmutableMap.of("a", 1, "b", 2)
  • using a Builder, for example,


public static final ImmutableSet<Color> GOOGLE_COLORS =
   ImmutableSet.<Color>builder()
       .addAll(WEBSAFE_COLORS)
       .add(new Color(0, 191, 255))
       .build();

Except for sorted collections, order is preserved from construction time. For example,



ImmutableSet.of("a", "b", "c", "a", "d", "b")

will iterate over its elements in the order "a", "b", "c", "d".


copyOf is smarter than you think


It is useful to remember that ImmutableXXX.copyOf attempts to avoid copying the data when it is safe to do so -- the exact details are unspecified, but the implementation is typically "smart". For example,



ImmutableSet<String> foobar = ImmutableSet.of("foo", "bar", "baz");
thingamajig(foobar);

void thingamajig(Collection<String> collection) {
   ImmutableList<String> defensiveCopy = ImmutableList.copyOf(collection);
   ...
}

In this code, ImmutableList.copyOf(foobar) will be smart enough to just return foobar.asList(), which is a constant-time view of the ImmutableSet.


As a general heuristic, ImmutableXXX.copyOf(ImmutableCollection) tries to avoid a linear-time copy if


  • it's possible using the underlying data structures in constant time. For example, ImmutableSet.copyOf(ImmutableList) can't be done in constant time.
  • it wouldn't cause memory leaks -- for example, if you have ImmutableList<String> hugeList, and you do ImmutableList.copyOf(hugeList.subList(0, 10)), an explicit copy is performed, so as to avoid accidentally holding on to references in hugeList that aren't needed.
  • it won't change semantics -- so ImmutableSet.copyOf(myImmutableSortedSet) will perform an explicit copy, because the hashCode() and equals used by ImmutableSet have different semantics from the comparator-based behavior of ImmutableSortedSet.

This helps minimize the performance overhead of good defensive programming style.


asList


All immutable collections provide an ImmutableList view via asList(), so -- for example -- even if you have data stored as an ImmutableSortedSet, you can get the kth smallest element with sortedSet.asList().get(k).


The returned ImmutableList is frequently -- not always, but frequently -- a constant-overhead view, rather than an explicit copy. That said, it's often smarter than your average List -- for example, it'll use the efficient contains methods of the backing collection.


Details


Where?


InterfaceJDK or Guava?Immutable Version
Collection JDK ImmutableCollection
List JDK ImmutableList
Set JDK ImmutableSet
SortedSet/NavigableSet JDK ImmutableSortedSet
Map JDK ImmutableMap
SortedMap JDK ImmutableSortedMap
Multiset Guava ImmutableMultiset
SortedMultiset Guava ImmutableSortedMultiset
Multimap Guava ImmutableMultimap
ListMultimap Guava ImmutableListMultimap
SetMultimap Guava ImmutableSetMultimap
BiMap Guava ImmutableBiMap
ClassToInstanceMap Guava ImmutableClassToInstanceMap
Table Guava ImmutableTable

Google Guava官方教程(中文版)

Google Guava官方教程(英文版)

标签:ImmutableSet,Core,use,collection,Libraries,copyOf,Guava,example
来源: https://www.cnblogs.com/ncore/p/10470569.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有