`

Google Guava API学习笔记(1):基础

 
阅读更多
   Guava项目包括了多个Google的核心库,包括collections、caching、primitives 、concurrency libraries、common annotations、string processing、I/O等,他们被广泛用于Google项目的开发。

学习地址:http://code.google.com/p/guava-libraries/wiki/GuavaExplained?tm=6

[size=x-lOptional:通过它避免使用null,或说避免null的歧义性[/size]


    避免用null,null是造成BUG的罪魁祸首,举个例子,通过Map#get(key),返回是null,既有可以是没有该键,也有可能是键对应的值是null,这种似是而非的情况容易造成程序Bug。

    为解决这个问题,Guava引入了一个Optional:

    来看一个Optional的使用:
   Optional<Integer> possible = Optional.of(5);//创建一个整数Optional对象
   possible.isPresent(); // returns true
   possible.get(); // returns 5

   如果possible不赋值,则isPresent()为false,否则为true,这样就避免了进行 == null的判断。
  
   Optional可以是任何的对象的封装对象,有了它,你就可以避免使用 ==null的判断了。

   它有3个静态方法:
|Optional.of(T) | Make an Optional containing the given non-null value, or fail fast on null.|
|Optional.absent() | Return an absent Optional of some type.|
|Optional.fromNullable(T) |Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent.|

   另外还有几个非表态方法:

boolean isPresent() Returns true if this Optional contains a non-null instance.
T get() Returns the contained T instance, which must be present; otherwise, throws an IllegalStateException.
T or(T) Returns the present value in this Optional, or if there is none, returns the specified default.
T orNull() Returns the present value in this Optional, or if there is none, returns null. The inverse operation of fromNullable.
Set<T> asSet() Returns an immutable singleton Set containing the instance in this Optional, if there is one, or otherwise an empty immutable set.


Preconditions:一般用于方法入参校验

    入参预校验,保证方法入参的合法性,及时抛出异常。相当于Spring 的Assert.notNull,Assert.notEmpty的功用,如:

checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s > %s", i, j);



用于排序的比较器

Ordering

   比较器类,可以很方便地扩展之:
Ordering<String> byLengthOrdering = new Ordering<String>() {
     public int compare(String left, String right) {
       return Ints.compare(left.length(), right.length());
     }
   };

if (Ordering.from(comparator).reverse().isOrdered(list)) { ... }


构造Ordering实现
拥有多个静态方法,方便构造出Ordering实例,如:

natural() Uses the natural ordering on Comparable types.
usingToString() Compares Objects by the lexicographical ordering of their string representations, as returned by toString().
arbitrary() Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality). There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM.


对Ordering进行控制

reverse() Returns the reverse ordering.
nullsFirst() Returns an Ordering that orders nulls before non-null elements, and otherwise behaves the same as the original Ordering. See also nullsLast().
compound(Comparator) Returns an Ordering which uses the specified Comparator to "break ties."
lexicographical() Returns an Ordering that orders iterables lexicographically by their elements.
onResultOf(Function) Returns an Ordering which orders values by applying the function to them and then comparing the results using the original Ordering.

  nullsFirst()方法显式指定对null这位怪人才要如何处理,对应的有nullsLast()

  假设我们希望按sortedBy字段进行排序:
class Foo {
  @Nullable String sortedBy;
  int notSortedBy;
}


下面的这个排序可以处理可能含有null的sortedBy问题:

Ordering<Foo> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Foo, String>() {
    public String apply(Foo foo) {
      return foo.sortedBy;
    }
  });


对Ordering常用方法

Method Description See also
greatestOf(Iterable iterable, int k) Returns the k greatest elements of the specified iterable, according to this ordering, in order from greatest to least. Not necessarily stable.leastOf
isOrdered(Iterable) Tests if the specified Iterable is in nondecreasing order according to this ordering.isStrictlyOrdered
sortedCopy(Iterable) Returns a sorted copy of the specified elements as a List.immutableSortedCopy
min(E, E) Returns the minimum of its two arguments according to this ordering. If the values compare as equal, the first argument is returned.max(E, E)
min(E, E, E, E...) Returns the minimum of its arguments according to this ordering. If there are multiple least values, the first is returned.max(E, E, E, E...)
min(Iterable) Returns the minimum element of the specified Iterable. Throws a NoSuchElementException if the Iterable is empty.max(Iterable), min(Iterator), max(Iterator)


Object通用方法的处理

Object定义了若干通用的方法,包括equals,toString等,子类要实现它们往往比较烦人(简单是简单,但大量重复性劳动)

equals

面对null不再需要特殊处理了:
Objects.equal("a", "a"); // returns true
Objects.equal(null, "a"); // returns false
Objects.equal("a", null); // returns false
Objects.equal(null, null); // returns true



hashCode
 
Objects.hashCode(field1, field2, ..., fieldn)

  想基于哪些字段产生hashCode,直接指定就可以了。

toString

类似地:
 Objects.toStringHelper(this)
       .add("x", 1)
       .toString();

   // Returns "MyObject{x=1}"
   Objects.toStringHelper("MyObject")
       .add("x", 1)
       .toString();


compare/compareTo
 
   考虑下面的这段“原始”代码:
class Person implements Comparable<Person> {
  private String lastName;
  private String firstName;
  private int zipCode;
  
  public int compareTo(Person other) {
    int cmp = lastName.compareTo(other.lastName);
    if (cmp != 0) {
      return cmp;
    }
    cmp = firstName.compareTo(other.firstName);
    if (cmp != 0) {
      return cmp;
    }
    return Integer.compare(zipCode, other.zipCode);
  }
}

 
  使用ComparisonChain进行排序:
public int compareTo(Foo that) {
     return ComparisonChain.start()
         .compare(this.aString, that.aString)
         .compare(this.anInt, that.anInt)
         .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
         .result();
   }

  注意anEnum是一个数组或List ,都可以了。


处理异常
  
  在tye/catch中处理一些异常,传播另一些异常:
 try {
     someMethodThatCouldThrowAnything();
   } catch (IKnowWhatToDoWithThisException e) {
     handle(e);
   } catch (Throwable t) {
     Throwables.propagateIfInstanceOf(t, IOException.class);
     Throwables.propagateIfInstanceOf(t, SQLException.class);
     throw Throwables.propagate(t);
   }


Signature Explanation
RuntimeException propagate(Throwable) Propagates the throwable as-is if it is a RuntimeException or an Error, or wraps it in a RuntimeException and throws it otherwise. Guaranteed to throw. The return type is a RuntimeException so you can write throw Throwables.propagate(t) as above, and Java will realize that that line is guaranteed to throw an exception.
void propagateIfInstanceOf(Throwable, Class<X extends Exception>) throws X Propagates the throwable as-is, if and only if it is an instance of X.
void propagateIfPossible(Throwable) Throws throwable as-is only if it is a RuntimeException or an Error.
void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X Throws throwable as-is only if it is a RuntimeException, an Error, or an X.


通过如下方法获取异常迹:

Throwable getRootCause(Throwable)
List<Throwable> getCausalChain(Throwable)
String getStackTraceAsString(Throwable)



 
3
5
分享到:
评论

相关推荐

    guava代码展示

    Guava的学习笔记.docx文件可能包含了对以上概念的详细解释和示例代码,而未命名的压缩包子文件可能是实际的代码示例或者更深入的案例研究。通过阅读这些材料,你可以深入了解Guava库的用法,并将其应用于你的项目中...

    996视频学习笔记-20211115.docx

    Guava是Google提供的一个强大的Java库,提供了许多实用功能,例如集合框架的扩展、缓存、并发工具等。在处理空集合时,Guava提供了更安全的API。比如,Guava的`Optional&lt;T&gt;`类可以用来表示一个值可能存在也可能不...

    一个轻量级,高性能的缓存构架,以android缓存而设计为初衷,也可以应用于一般的Java项目中。.zip

    6. **Guava Cache**:Google的Guava库提供了强大的缓存功能,可能会详细讲解如何使用Guava Cache构建和管理缓存。 7. **JCache(JSR 107)**:Java标准的缓存API,介绍如何利用JCache接口进行缓存操作,以及它与...

    PubLearnNotes

    【标题】"PubLearnNotes" 是一个公开的学习笔记集合,主要涵盖了作者在IT领域的学习历程,尤其是关于Java编程语言的知识点。这个资源可能是作者为了方便自己随时查阅和更新而创建的,同时也分享给了对相关技术感兴趣...

    tpLectorDeNotas

    若选择云存储,如Google Drive或Dropbox,可能需要集成对应的API。 在实现过程中,Java的多线程技术也发挥了重要作用。比如,为了保证用户界面的响应性,后台任务(如读写文件或网络通信)通常会在单独的线程中执行...

Global site tag (gtag.js) - Google Analytics