package datastructure.delme;
import java.util.*;
class SimpleClass {
private String desc;
public SimpleClass(String s) {
desc=s;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "description is "+desc;
}
}
public class DelMeCollection {
public static void main(String[] args) {
System.out.println("in main");
SimpleClass s1 = new SimpleClass("one");
SimpleClass s2 = new SimpleClass("two");
SimpleClass s3 = new SimpleClass("three");
SimpleClass s4 = new SimpleClass("four");
HashMaphm = new HashMap ();
hm.put("1",s1);
hm.put("2",s2);
hm.put("3",s3);
hm.put("4",s4);
Iterator hmKeyItr = hm.keySet().iterator();
while(hmKeyItr.hasNext())
{
String tempKey= (String)hmKeyItr.next();
System.out.println(tempKey+" val is "+hm.get(tempKey));
}
Iterator hmValItr = hm.values().iterator();
while(hmValItr.hasNext())
{
SimpleClass tempVal = (SimpleClass)hmValItr.next();
System.out.println(" val is "+tempVal);
}
for (Map.Entryentry: hm.entrySet())
{
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
also tried UPCASTING
the following gave error
HashMap < string , object > hm = new HashMap < string , simpleclass >();
HashMap < string , simpleclass > hm = new HashMap < string , object >();
HashMap < string , simpleclass > hm = new HashMap < object , sipleclass >();
HashMap < object , simpleclass > hm = new HashMap< string , simpleclass >();
Moreover java.util.HashMap
Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new HashMap(...));
No comments:
Post a Comment