Advertisement
Guest User

Hashing

a guest
Apr 3rd, 2011
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. public class Customer {
  2.  
  3.     private String firstName;
  4.     private String lastName;
  5.     private Date birthday;
  6.     private String street;
  7.     private String city;
  8.     private String zipcode;
  9.  
  10.     protected boolean equalFields(Customer rhs) {
  11.         return ObjectUtils.eqFields(firstName, rhs.firstName) &&
  12.                ObjectUtils.eqFields(lastName, rhs.lastName) &&
  13.                ObjectUtils.eqFields(birthday, rhs.birthday) &&
  14.                ObjectUtils.eqFields(city, rhs.city) &&
  15.                ObjectUtils.eqFields(zipcode, rhs.zipcode);
  16.     }
  17.  
  18.     @Override
  19.     public boolean equals(Object obj) {
  20.         if (this == obj) return true;
  21.         return (obj instanceof Customer &&
  22.                 ((Customer)obj).equalFields(this));
  23.     }
  24.  
  25.     @Override
  26.     public int hashCode() {
  27.         int result = 21 + ObjectUtils.hash(birthday);
  28.         result = result * 31 + ObjectUtils.hash(city);
  29.         result = result * 31 + ObjectUtils.hash(firstName);
  30.         result = result * 31 + ObjectUtils.hash(lastName);
  31.         result = result * 31 + ObjectUtils.hash(street);
  32.         return result * 31 + ObjectUtils.hash(zipcode);
  33.     }
  34. }
  35.  
  36. // this class would be public in a package say utils
  37. class ObjectUtils {
  38.     public static boolean eqFields (Object a, Object b) {
  39.         if (a != null)
  40.             return a.equals(b);
  41.         else
  42.             return (b == null);
  43.     }
  44.  
  45.     public static int hash(Object obj) {
  46.         return ((obj == null) ? 0 : obj.hashCode());
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement