Saturday, 28 April 2018

//How to eliminate duplicate user defined objects from HashSet?

package collectctiondemo;

public class Price {

private String item;
private int price;
public Price(String item, int price) {
super();
this.item = item;
this.price = price;
}
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;
}




@Override
public String toString() {
return "Price [item=" + item + ", price=" + price + "]";
}
public int hashCode(){
        System.out.println("In hashcode");
        int hashcode = 0;
        hashcode = price*20;
        hashcode += item.hashCode();
        System.out.println(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;
        }
        }
    }

==============================================================================================

package collectctiondemo;

import java.util.HashSet;
import java.util.Set;

public class PriceMain {

public static void main(String a[]){
       
       Set<Price> s = new HashSet<Price>();
        s.add(new Price("laptop",40000));
        s.add(new Price("mobile", 10000));
        s.add(new Price("computer",30000));
        for(Price p:s){
            System.out.println(p);
        }
        Price duplicate = new Price("mobile",10000);
        System.out.println("inserting duplicate object...");
        s.add(duplicate);
        System.out.println("After insertion:");
        for(Price p:s){
            System.out.println(p.getItem()+" "+p.getPrice());
        }
}



}


===============================================================================================


o/p view:---------------------------------
In hashcode
-1109185830
In hashcode
-1068655134
In hashcode
-598563109
Price [item=laptop, price=40000]
Price [item=computer, price=30000]
Price [item=mobile, price=10000]
inserting duplicate object...
In hashcode
-1068655134
In equals
After insertion:
laptop 40000
computer 30000
mobile 10000

No comments:

Post a Comment