Java基礎工具--Guava Libraries學習筆記

jopen 10年前發布 | 17K 次閱讀 Guava 常用工具包

什么是Guava-Libraries?

Guava-Libraries是google對java的一個擴展,主要涵蓋集合、緩存、并發、I/O、反射等等。

它本來是Google內部所使用的一個類庫,后來整理開源出來了。這套庫的設計引入了很多新的理念,研究一下可能會使你對Java這門語言有新的認識和看法。

地址:http://code.google.com/p/guava-libraries/

這篇短文主要是關于Guava-Libraries基礎工具,內容是我參考官方wiki和自己的使用體驗結合而成。

null的使用

null在java中是一個很特殊的東西。它可以標識一個不確定的對象,比如

Ojbect o = null
     </div>

</td>

   </tr>

  </tbody>

 </table>

</div>

</div>

</div>

同時在很多個集合中它代表key不存在,也可以代表值為null。

null使用需要給外的小心,稍不注意就會出現很多問題。當然更多的時候只是單純的覺得null不夠優雅而已。

Guava為我們提供了一個Optional的抽象類來解決這個問題。用類Present和Absent代表值存在和不存在。

以下是一個例子:

Optional possible = Optional.of( 5 );
if (possible.isPresent()) {
    System.out.println(possible.get());
}

Optional absentValue = Optional. absent();
if (absentValue.isPresent())
   System.out.println(absentValue.get());
System.out.println(absentValue.or(- 1 ));
System.out.println(absentValue.orNull());
System.out.println(absentValue.asSet());

</div>

</div>

</div>

第一種是值存在的,第二種是值不存在的。執行效果如下:

Java基礎工具--Guava-Libraries學習筆記

這里說明一下isPresent()方法是判斷是否有值的。or方法是非null返回Optional的值,否則返回傳入值。

orNull()方法是非null返回Optional的值,否則返回null。

我個人覺得or方法比較常用就是了。

條件判斷

Guava還封裝了一些條件檢查方法,比如判斷真假、判斷是否為空、判斷index是否合法等等。如果判斷通過,返回值本身,否則拋出錯誤。

每種方法又對應了三種重載:

1.沒有錯誤信息

2.有直接的錯誤信息

3.帶模板的錯誤信息

來個小例子:

int i = Preconditions.checkNotNull( null );
int i2 = Preconditions.checkNotNull( null , "錯誤" );
int i3 = Preconditions.checkNotNull( null , "錯誤:%s" , "001" );

</div>

</div>

效果如下:

Java基礎工具--Guava-Libraries學習筆記
Java基礎工具--Guava-Libraries學習筆記
Java基礎工具--Guava-Libraries學習筆記

對象的常用方法

簡單實現了Object的一些方法而已,比如toString、hashCode。

我個人覺得equal這塊用戶不大,主要是toString和Compare。

特別是ComparisonChain的使用,有種鏈式編程的感覺。

例子:

System.out.println( "a equal a :" + Objects.equal( "a" , "a" ));
System.out.println( "a equal b :" + Objects.equal( "a" , "b" ));

System.out.println( "hascode : "
         + Objects.hashCode( "one" , "two" , 3 , 4.0 ));

System.out.println( "Blog toString : "
         + Objects.toStringHelper( "Blog" ).add( "name" , "huang" )
                 .add( "url" , "http://htynkn.cnblogs.com/" ).toString());

System.out.println(ComparisonChain.start().compare( 1.0 , 1 )
         .compare( "a" , "a" ).compare( 1.4411 , 1.441 ).result());

</div>

</div>

效果:

Java基礎工具--Guava-Libraries學習筆記

來自:http://www.cnblogs.com/htynkn/archive/2012/08/19/2646798.html
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
  • sesese色