|
|
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?
|
|
|
doPost Vs doGet methods
doGet() method is used to get information, while doPost() method is used for posting information. doGet() requests can't send large
amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length.
A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas
a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
It is easier to fight for one’s principles than to live up to them.
-- Alfred Adler
|