How to delete user defined objects as a key from Linked HashMap
package com.java2novice.linkedhashmap;
import java.util.LinkedHashMap;
import java.util.Set;
public class MyDeleteKeyObject
{
public static void main(String a[])
{
LinkedHashMap hm = new LinkedHashMap();
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 map)
{
Set
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;
}
}
How to add all elements to the given collection object
package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsAddAll
{
public static void main(String a[])
{
List
myList = new ArrayList();
myList.add("java");
myList.add("c");
myList.add("c++");
System.out.println("Initial
list:"+myList);
Collections.addAll(myList,
"perl","php");
System.out.println("After
adding elements:"+myList);
String[]
strArr = {".Net", "unix"};
Collections.addAll(myList,
strArr);
System.out.println("After
adding array:"+myList);
}
}
Write an example for Collections.as LifoQueue() method
package com.java2novice.collections;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;
public class CollectionAsLifoQueue
{
public static void main(String args[])
{
Deque
dq = new ArrayDeque(5);
dq.add("java");
dq.add("c");
dq.add("c++");
dq.add("unix");
dq.add("perl");
Queue
q = Collections.asLifoQueue(dq);
System.out.println("returned
queue is: "+q);
}
}
No comments:
Post a Comment