|
|
Program: How to delete user defined objects from HashSet?
Description: |
Below example shows how to delete 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 MylhsDeleteObject {
public static void main(String a[]){
HashSet<Price> lhs = new HashSet<Price>();
lhs.add(new Price("Banana", 20));
lhs.add(new Price("Apple", 40));
lhs.add(new Price("Orange", 30));
for(Price pr:lhs){
System.out.println(pr);
}
Price key = new Price("Banana", 20);
System.out.println("deleting key from set...");
lhs.remove(key);
System.out.println("Elements after delete:");
for(Price pr:lhs){
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: Banana price: 20
item: Apple price: 40
item: Orange price: 30
deleting key from set...
In hashcode
In equals
Elements after delete:
item: Apple price: 40
item: Orange price: 30
|
|
|
|
|
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?
|
|
|
What is servlet context?
The servlet context is an interface which helps to communicate with
other servlets. It contains information about the Web application and
container. It is kind of application environment. Using the context, a
servlet can obtain URL references to resources, and store attributes that
other servlets in the context can use.
There is a great difference between worry and concern. A worried person sees a problem, and a concerned person solves a problem.
-- Harold Stephens
|