|
|
Program: How to delete user defined objects as a key from LinkedHashMap?
Description: |
Below example shows how to delete user defined objects as a key from LinkedHashMap.
You can achieve this by implementing equals and hashcode methods at the user defined objects.
|
Code: |
package com.java2novice.linkedhashmap;
import java.util.LinkedHashMap;
import java.util.Set;
public class MyDeleteKeyObject {
public static void main(String a[]){
LinkedHashMap<Price, String> hm = new LinkedHashMap<Price, String>();
hm.put(new Price("Banana", 20), "Banana");
hm.put(new Price("Apple", 40), "Apple");
hm.put(new Price("Orange", 30), "Orange");
printMap(hm);
Price key = new Price("Banana", 20);
System.out.println("Deleting key...");
hm.remove(key);
System.out.println("After deleting key:");
printMap(hm);
}
public static void printMap(LinkedHashMap<Price, String> map){
Set<Price> keys = map.keySet();
for(Price p:keys){
System.out.println(p+"==>"+map.get(p));
}
}
}
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: |
item: Apple price: 40==>Apple
item: Orange price: 30==>Orange
item: Banana price: 20==>Banana
Deleting key...
After deleting key:
item: Apple price: 40==>Apple
item: Orange price: 30==>Orange
|
|
|
|
|
List Of All LinkedHashMap Sample Programs:- LinkedHashMap basic operations
- How to iterate through LinkedHashMap?
- How to check whether the value exists or not in a LinkedHashMap?
- How to delete all entries from LinkedHashMap object?
- How to eliminate duplicate user defined objects as a key from LinkedHashMap?
- How to find user defined objects as a key from LinkedHashMap?
- How to delete user defined objects as a key from LinkedHashMap?
|
|
|
What is wrapper class?
Everything in java is an object, except primitives. Primitives are
int, short, long, boolean, etc. Since they are not objects, they cannot
return as objects, and collection of objects. To support this, java provides
wrapper classes to move primitives to objects. Some of the wrapper classes
are Integer, Long, Boolean, etc.
The greatest obstacle to discovery is not ignorance; it is the illusion of knowledge.
-- Daniel J. Boorstin
|