Menu



Java program to implement hashcode and equals


HashcodeEqual.java

import java.util.HashMap;
public class HashcodeEqual {
public static void main(String a[]){
HashMap<Price, String> h1 = new HashMap<Price, String>();
h1.put(new Price("shirt", 20), "shirt");
h1.put(new Price("jeans", 40), "jeans");
h1.put(new Price("shoes", 30), "shoes");
Price key = new Price("shirt", 20);
System.out.println("Hashcode of the key: "+key.hashCode());
System.out.println("Value from map: "+h1.get(key));
}
}
class Price{
private String item;
private int price;
public Price(String itm, int pr){
this.item = itm;
this.price = pr;
}
public int hashCode(){
System.out.println("In hashcode");
int hashcode = 0;
hashcode = price*20;
hashcode += item.hashCode();
return hashcode;
}
public boolean equals(Object obj){
System.out.println("In equals");
if (obj instanceof Price) {
Price pp = (Price) obj;
return (pp.item.equals(this.item) && pp.price == this.price);
} else {
return false;
}
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString(){
return "item: "+item+" price: "+price;
}
}










Connection failed: SQLSTATE[28000] [1045] Access denied for user 'studentdb'@'localhost' (using password: YES)

Subscribe