Advertisement
apl-mhd

HashCode and Equals method overide

Dec 29th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.HashMap;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) {
  8.     // write your code here
  9.  
  10.         HashMap<Object,Integer> hashMap = new HashMap<>();
  11.  
  12.         HashMap<Person,Boolean> personHashMap = new HashMap<>();
  13.  
  14.  
  15.         String a="a";
  16.         String b="a";
  17.  
  18.         hashMap.put(a,10);
  19.         hashMap.put(b,20);
  20.  
  21.         //System.out.println(hashMap.size());
  22.  
  23.         Person arr[] = new Person[5];
  24.         arr[0] = new Person("Apel","36");
  25.         arr[1] = new Person("Sabi","36");
  26.         arr[2] = new Person("Orin","36");
  27.         arr[3] = new Person("Nawsin","36");
  28.         arr[4] = new Person("Nawsin","36");
  29.  
  30. /*
  31.         if(arr[4].equals(arr[3]))
  32.             System.out.println(true);
  33.         else
  34.             System.out.println(false);
  35.  
  36. */
  37.  
  38.  
  39.         personHashMap.put(arr[0],true);
  40.         personHashMap.put(arr[1],true);
  41.         personHashMap.put(arr[2],false);
  42.  
  43.         System.out.println(personHashMap.size());
  44.  
  45.         System.out.println(personHashMap.get(arr[0]));
  46.         System.out.println(personHashMap.get(arr[2]));
  47.  
  48.  
  49.  
  50.  
  51.     }
  52. }
  53.  
  54.  
  55. package com.company;
  56.  
  57. public class Person {
  58.  
  59.     String firstName;
  60.     String id;
  61.  
  62.     public Person(String firstName, String id) {
  63.         this.firstName = firstName;
  64.         this.id = id;
  65.     }
  66.  
  67.  
  68.     public  int hashCode(){
  69.  
  70.         int hashcode=0;
  71.         hashcode +=id.hashCode();
  72.  
  73.         return hashcode;
  74.     }
  75.  
  76.  /*   @Override
  77.     public String toString() {
  78.         return firstName+" "+id;
  79.     }
  80. */
  81.  
  82.  
  83.     public boolean equals(Object o){
  84.  
  85.         if (o instanceof Person) {
  86.             Person p = (Person) o;
  87.         return id==p.id;
  88.         }
  89.         else
  90.             return false;
  91.     }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement