Guava Study Notes: Object encapsulation operations in guava
Reprint: Http://outofmemory.cn/java/guava/base/Objects
We often need to compare two objects for equality in development, when we need to consider whether the comparison of two objects is null, and then call the Equals method to compare equality, Google The Com.google.common.base.Objects class of the guava library provides a static method that equals can prevent us from making an empty judgment, as shown in the following example:
Object=null; Object=Newobject(); Boolean=Objects. Equal(a, b);
The implementation of Objects.equals is perfect, and its implementation code is as follows:
Public Static BooleanEqual( @Nullable object A,< Span class= "PLN" > @Nullable object B) { return a == b | | (a != Null && A.b
First determine whether a B is the same object, if it is the same object, then return the equality directly, if not the same object then judge A is not null and a.equals (b). Doing so takes into account both performance and NULL NULL pointer issues.
In addition, the objects class also provides us with a convenient way to rewrite the ToString () method, let's take a look at the example:
Packagecn.OutOfMemory.Guava.Base;ImportCom.Google.Common.Base.Objects;Public Class Objectsdemo {Public Static voidMain(String []Args) {StudentJim= New Student();Jim.SetId(1);Jim.SetName("Jim");Jim.Setage(13);System.Out.println(Jim.Tostring());}Public Static Class Student {Private IntId;Private StringName;Private IntAge;Public IntGetId() {ReturnId;}Public voidSetId(IntId) {This.Id=Id;}Public StringGetName() {ReturnName; }Public voidSetName(StringName) {This.Name=Name;}Public IntGetage() {ReturnAge;}Public voidSetage(IntAge) {This.Age=Age;}Public StringTostring() {Return Objects.Tostringhelper(This.GetClass()).Add("id",Id) add ( "name" , Name add ( "age" , Age omitnullvalues (). } } /span>
We define a student class that has three properties, id,name,age, and we rewrite the ToString () method, In this method we use the Objects.tostringhelper method, first specifying the ToString class, then the Add property name and the property value, you can use the Omitnullvalues () method to specify that the null value is ignored, and finally call its ToString () method, you can get a well-formed ToString implementation.
The result of the above code output is:
Student{id=1, name=Jim, age=all}
This is a simple way to write, and readability is very good, so use guava bar.
Guava Study Notes: Object encapsulation operations in guava