Sunday 9 August 2015

Guava : Objects class


Objects class provides number of helper functions to operate on java objects. By using Objects class, you can generate hashCode, toString method effectively. Following example explains that.
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;

public class Employee {
  private String firstName;
  private String lastName;
  private int age;

  Employee(String firstName, String lastName, int age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String toString() {
    return MoreObjects
        .toStringHelper(this)
        .omitNullValues()
        .add("firstName",
            MoreObjects.firstNonNull(firstName, "No first name"))
        .add("lastName",
            MoreObjects.firstNonNull(lastName, "No last name"))
        .add("age", MoreObjects.firstNonNull(age, "age not exist"))
        .toString();

  }

  @Override
  public int hashCode() {
    return Objects.hashCode(firstName, lastName, age);
  }
}

public class EmployeeTest {
  public static void main(String args[]) {
    Employee emp = new Employee("Hari Krishna", null, 26);
    System.out.println(emp.hashCode());
    System.out.println(emp);
  }
}

Output
487116915
Employee{firstName=Hari Krishna, lastName=No last name, age=26}

If you want to override hashcode manually, go through following post.


Objects class provides equals() method which is used to compare two objects.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment