"The beauty of Java code"---the Common method of Guava Replication object

Source: Internet
Author: User

Common methods of Guava Replication object

Guava is an extension project for Google's java1.6-based class library collection, which provides practical methods for collections, caches, support primitives, concurrency, common annotations, string handling, I/O, and validation.

These high-quality APIs can make your Java code more elegant and concise, making your work easier and more enjoyable.

I. Overview

In Java, the object class is the parent class for all classes, and there are several methods that require override, such as Equals,hashcode and ToString. Every time you write these methods, you have to make a lot of repetitive judgments,

Many class libraries provide a tool class for covering these methods, and guava provides a similar approach. Let's take a look at some of these methods in guava simple use.

The objects class in guava provides many of the same and more efficient ways to use the object class:

1. Equal method

Equality is judged using the Equals method of obejct, for example: Test.equals ("Test"), or if test is null, the equal method of nullpointerexception,objects will occur to help you

Avoid nullpointerexception, and its judgment logic is this: return a = = B | | (a!=null&& a.equals (b)); So, it can be very reassuring to use,objects.equal (test, "test")

Of course, the same method of judging logic is also provided in JDK7: Objects.equals (Test, "test");

 public  class   Objecttest {@Test  void   Equaltest () {System.out.println (Objects.equal (" A "," a ")); System.out.println (objects.equal ( null , "a"          "A", null           null , null      /**   output result * true * false * false * true  */ 
2. Hashcode method

For Hashcode first to understand two points:

1. If Equals () determines that two objects are equal, then their hashcode () method must return the same value.

2. There is no mandatory requirement if equals () determines that two objects are not equal, their hashcode can be the same or different.

Guava provides us with a simpler way of--objects.hashcode (Object ...), which is a variable parameter method, and the argument list can be any number, so you can

Use Objects.hashcode (field1, Field2, ..., fieldn). Very convenient and concise.

Importorg.junit.Test;Importcom.google.common.base.Objects; Public classobjecttest {@Test Public voidhashcodetest () {System.out.println (Objects.hashcode (A)); System.out.println (Objects.hashcode (A)); System.out.println (Objects.hashcode ("A", "B")); System.out.println (Objects.hashcode ("B", "a")); System.out.println (Objects.hashcode ("A", "B", "C")); Person Person=NewPerson ("Peida", 23);        System.out.println (Objects.hashcode (person));    System.out.println (Objects.hashcode (person)); }}classPerson { PublicString name;  Public intAge ; Person (String name,intAge ) {         This. Name =name;  This. Age =Age ; }}
// Output Results 128406640961261451931325619313256
3. Tostringhelper () method

Because each class inherits directly or indirectly from object, each class has the ToString () method. This method is most used, the most overwrite, a good ToString method is very important for debugging,

But it really sucks to write. Guava also provides the ToString () method.

Use the Tostringhelper method to output the attribute fields you need to output

Importorg.junit.Test;Importcom.google.common.base.Objects; Public classobjecttest {@Test Public voidtostringtest () {//this represents the current class, where only the X attribute field is outputSystem.out.println (Objects.tostringhelper ( This). Add ("X", 1). toString ()); //represents the output object as a person object
System.out.println (Objects.tostringhelper (Person.class). Add ("X", 1). ToString ());//Add can overlayPerson person=NewPerson ("Peida", 23); String result= Objects.tostringhelper (person.class). Add ("Name", Person.name). Add ("Age", Person.age). toString (); System.out.print (result); }}classPerson { PublicString name; Public intAge ; Person (String name,intAge ) { This. Name =name; This. Age =Age ; }}//============ Output ===============Objecttest{x=1}person{x=1}person{name=peida, age=23}
4. Firstnonnull Method

The Firstnonnull method of object can return a non-null parameter based on the two parameters passed in, and guava now recommends replacing it with Moreobjects.firstnonnull (T first,t second) .

Importcom.google.common.base.MoreObjects; Public classTestfilter { Public Static voidMain (string[] args) {//name is not emptyString name= "Zhang San"; String Nann= Moreobjects.firstnonnull (name, "haha");      System.out.println (Nann); //sex is nullString sex=NULL; String Sexx= Moreobjects.firstnonnull (Sex, "haha");    System.out.println (Sexx); }    /** Operation Result: * Zhang San * haha*/}

In practical development, objects.equal (test, "test") and Moreobjects.firstnonnull (T first,t second) are very helpful in many practical situations.

think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Lieutenant Colonel "11"

"The beauty of Java code"---the Common method of Guava Replication object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.