Advertisement
apl-mhd

HashCode

Dec 27th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.HashMap;
  4.  
  5.         import java.util.HashMap;
  6.  
  7.  class MyHashcodeImpl {
  8.  
  9.     public static void main(String a[]){
  10.  
  11.         HashMap<Price, String> hm = new HashMap<Price, String>();
  12.         hm.put(new Price("Banana", 20), "Banana");
  13.         hm.put(new Price("Apple", 40), "Apple");
  14.         hm.put(new Price("Orange", 30), "Orange");
  15.         //creating new object to use as key to get value
  16.         Price key = new Price("Baanana", 200);
  17.         System.out.println("Hashcode of the key: "+key.hashCode());
  18.         System.out.println("Value from map: "+hm.get(key));
  19.     }
  20. }
  21.  
  22. public  class Price {
  23.  
  24.     private String item;
  25.     private int price;
  26.  
  27.     public Price(String itm, int pr){
  28.         this.item = itm;
  29.         this.price = pr;
  30.     }
  31.  
  32.     public int hashCode(){
  33.         System.out.println("In hashcode");
  34.         int hashcode = 0;
  35.         hashcode = price*20;
  36.         hashcode += item.hashCode();
  37.         return hashcode;
  38.     }
  39.  
  40.     public boolean equals(Object obj){
  41.         System.out.println("In equals");
  42.         if (obj instanceof Price) {
  43.             Price pp = (Price) obj;
  44.             return (pp.item.equals(this.item) && pp.price == this.price);
  45.         } else {
  46.             return false;
  47.         }
  48.     }
  49.  
  50.     public String getItem() {
  51.         return item;
  52.     }
  53.     public void setItem(String item) {
  54.         this.item = item;
  55.     }
  56.     public int getPrice() {
  57.         return price;
  58.     }
  59.     public void setPrice(int price) {
  60.         this.price = price;
  61.     }
  62.  
  63.     public String toString(){
  64.         return "item: "+item+"  price: "+price;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement