Advertisement
yo2man

Tutorial 41 The Equals Method

May 24th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. //Tutorial 41 The Equals Method
  2. //pretty easy straight forward stuff
  3. class Person {
  4.     private int id;
  5.     private String name;
  6.  
  7.     public Person(int id, String name) { //rightclick>source>generate constructor using fields>check all fields you want>delete "super()"
  8.         this.id = id;
  9.         this.name = name;
  10.     }
  11.  
  12.     @Override
  13.     public String toString() { //rightclick>source>generate toString>click the fields you want
  14.         return "Person [id=" + id + ", name=" + name + "]";
  15.     }
  16.  
  17.     @Override
  18.     public int hashCode() {  //to generate .equals method, rightclick>source>hashCode()andequals()>check the fields you want to compare
  19.         final int prime = 31;
  20.         int result = 1;
  21.         result = prime * result + id;
  22.         result = prime * result + ((name == null) ? 0 : name.hashCode());
  23.         return result;
  24.     }
  25.  
  26.     @Override  
  27.     public boolean equals(Object obj) {
  28.         if (this == obj)
  29.             return true;
  30.         if (obj == null)
  31.             return false;
  32.         if (getClass() != obj.getClass())
  33.             return false;
  34.         Person other = (Person) obj;
  35.         if (id != other.id)
  36.             return false;
  37.         if (name == null) {
  38.             if (other.name != null)
  39.                 return false;
  40.         } else if (!name.equals(other.name))
  41.             return false;
  42.         return true;
  43.     }
  44.  
  45. }
  46.  
  47. public class App {
  48.  
  49.     public static void main(String[] args) {
  50.        
  51.         Person person1 = new Person(5, "Bob");
  52.         Person person2 = new Person(5, "Bob");
  53.        
  54.         person2 = person1;
  55.        
  56.             System.out.println(person1.equals(person2)); //.equalS to tell if values are equal
  57.     }  
  58. }
  59.  
  60. //---------------------------------------------------------------------------------------------------------------------------------------
  61. /* Run Results:
  62. True
  63. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement