|
|
Program: How to eliminate duplicate user defined objects from HashSet?
Description: |
Below example shows how to avoid duplicate user defined objects from HashSet.
You can achieve this by implementing equals and hashcode methods at the user defined objects.
|
Code: |
package com.java2novice.hashset;
import java.util.HashSet;
public class MyDistElementEx {
public static void main(String a[]){
HashSet<Price> lhm = new HashSet<Price>();
lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));
lhm.add(new Price("Orange", 30));
for(Price pr:lhm){
System.out.println(pr);
}
Price duplicate = new Price("Banana", 20);
System.out.println("inserting duplicate object...");
lhm.add(duplicate);
System.out.println("After insertion:");
for(Price pr:lhm){
System.out.println(pr);
}
}
}
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;
}
}
|
|
Output: |
In hashcode
In hashcode
In hashcode
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20
inserting duplicate object...
In hashcode
In equals
After insertion:
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20
|
|
|
|
|
List Of All HashSet Sample Programs:- Basic HashSet Operations.
- How to iterate through HashSet?
- How to copy Set content to another HashSet?
- How to delete all elements from HashSet?
- How to copy all elements from HashSet to an array?
- How to compare two sets and retain elements which are same on both sets?
- How to eliminate duplicate user defined objects from HashSet?
- How to find user defined objects from HashSet?
- How to delete user defined objects from HashSet?
|
|
|
Can we call servlet destory() from service()?
As you know, destory() is part of servlet life cycle methods, it is used to kill the
servlet instance. Servlet Engine is used to call destory(). In case, if you call destory
method from service(), it just execute the code written in the destory(), but it wont
kill the servlet instance. destroy() will be called before killing the servlet instance
by servlet engine.
I don’t know the key to success, but the key to failure is trying to please everybody.
-- Bill Cosby
|