Object methods commonly used in Guava - equals and null comparison, hashCode, custom toString, custom compareTo sorting

Scenes

Introduction to the Java core tool library Guava and the use of Optional and Preconditions for non-null and data validation:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127683387

Based on the introduction of Guava above, let's take a look at Guava's commonly used Object methods.

Note:

Blog:
https://blog.csdn.net/badao_liumang_qizhi
Pay attention to the public account
domineering programmer
Get programming-related eBooks, tutorial pushes, and free downloads.

Objects.equal

Implementing the Object.equals method requires null checking when a field in an object can be null.

All classes inherit Object by default, and also inherit the equals method, so when comparing whether the objects are equal, use a.equals(b) to compare directly. If a is empty, an exception will be reported.

        User user = new User();
        User user1 = null;
        System.out.println(user1.equals(user));//exception will be reported
        System.out.println(user.equals(user1));//false

In order to avoid using if(null!=a) to make judgments every time, use Guava's Objects.equal method to avoid

        System.out.println(Objects.equal(user,user));//true
        System.out.println(Objects.equal(user1,user));//false
        System.out.println(Objects.equal(null,null));//true

It should be noted that the same method is also provided in JDK7, so it can be used directly in Java.

hashCode

It should be simpler to do a hash operation with all the fields of the object.

Guava's Objects.hashCode computes a reasonable, order-sensitive hash value for the incoming field sequence.

It should be noted that the same method is also provided in JDK7.

toString

Good toString methods can help debugging better, but writing toString methods is a pain.

Use the MoreObjects.toStringHelper method to easily write useful toString methods.

When the class does not override the toString method, the object's toString method is called

Take a User class as an example

package com.ruoyi.demo.guava.basictools;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private Company company;
}

If you call its toString directly

        User user = new User("overbearing",50,new Company("Company Name","company address"));
        System.out.println(user.toString());
        //When the class is not overridden toString method will be called object of toString method
        //User(name=overbearing, age= 50,company=Company(name=Company Name, address= company address))

In order to facilitate debugging, after re-toString

package com.ruoyi.demo.guava.basictools;

import com.google.common.base.MoreObjects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private Company company;

    @Override
    public String toString() {
        return MoreObjects
                .toStringHelper(this)
                .add("Name", name)
                .add("age", age)
                .add("Only the company name is required", company.getName())
                .toString();
    }

}

Then output toString

        //To facilitate debugging, rewrite toString after method
        //User{Name=overbearing, age=50, Only the company name is required= Company Name}

Implement the Comparable interface and override the compareTo method

The Company class used above

package com.ruoyi.demo.guava.basictools;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company {
    private String name;
    private String address;
}

Implement the Comparable interface in this class because you want to sort objects of this class.

The sorting logic is written in the comparaTo method. I want to sort by name first, and if the names are the same, sort by address.

package com.ruoyi.demo.guava.basictools;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company implements Comparable{
    private String name;
    private String address;


    //exist Company implemented in the class Comparable interface because I want to sort objects of this class.
    // I'm already in compareTo()The sorting logic is written in the method, I want to sort by name first, and if the names are the same, sort by address
    @Override
    public int compareTo(Object o) {
        Company company = (Company) o;
        int result = name.compareTo(company.getName());
        if(result!=0){
            return result;
        }
        result = address.compareTo(company.address);
        return result;
    }
}

Using Guava's ComparisonChain to implement the Comparable interface can be written like this

package com.ruoyi.demo.guava.basictools;

import com.google.common.collect.ComparisonChain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company implements Comparable{
    private String name;
    private String address;

    //with the help of Guava ComparisonChain accomplish Comparable The interface can be written like this
    @Override
    public int compareTo(Object o) {
        Company company = (Company) o;
        return ComparisonChain.start()
                .compare(this.name,company.name)
                .compare(this.address,company.address)
                .result();
    }
}

This style is more readable, has less chance of miscoding, and avoids unnecessary work.

 

Tags: Java

Posted by kingpin393 on Fri, 04 Nov 2022 11:31:22 +0530