Wednesday, September 10, 2014

Using Objects in equals and hashcode methods for null safety

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Name {
       private String firstName;
       private String lastName;

       public Name(String firstName, String lastName) {
              this.firstName = firstName;
              this.lastName = lastName;
       }

       public String getFirstName() {
              return firstName;
       }

       public String getLastName() {
              return lastName;
       }

       @Override
       public String toString() {
              return "Name [firstName=" + firstName + ", lastName=" + lastName + "]";
       }

       @Override
       public int hashCode() {
              return 31 * Objects.hashCode(firstName) + Objects.hashCode(lastName);
       }

       @Override
       public boolean equals(Object obj) {
              if (this == obj) {
                     return true;
              }
              if (obj == null) {
                     return false;
              }
              if (getClass() != obj.getClass()) {
                     return false;
              }
              Name other = (Name) obj;
              return Objects.equals(this.firstName, other.firstName)
                           && Objects.equals(this.lastName, other.lastName);
       }

       public static void main(String[] args) {
              Name name1 = new Name("Lenin", "Kumar");
              Name name2 = new Name("Lenin", "Kumar");
              Name name3 = new Name("Lenin", "Kevin");
              System.out.println(name1.equals(name2));
              System.out.println(name1.equals(name3));
              Set names = new HashSet<>();
              names.add(name1);
              names.add(name2);
              names.add(name3);
              System.out.println(names);
       }
}

No comments:

Post a Comment