Add hashmap to hashmap

Hi all,
I have a hashmap inside hashmap - it is looking like that:
{Header7={z=8, Header1={m=19, n=20, l=18}},
Header2={d=4, k1=20, f=6, j1=10, e=5},
Header1={a=1, c=3, b=2},
Header6={d=4, f=6, e=5},
Header3={k=20, Header4={i=3, h=2, g=1}, j=10, Header5={g1=7, h1=8, i1=9}}}
Now I want to add to the one of the inner hash for example {Header1={d=4, f=6, e=5}}
So, i iterate, and run recursive till I got (d,4)...
now, what is the next step ?

It is not that easy, because now I need to iterate in
the original Hashmap to the correct HashMap
(Header1...) and I don't want to loose the data from
the toAdd HashMap.I don't get your point. Why do you lose any data, and why do you need to iterate through a Hashmap? Shouldn't you be doing a look-up?
Maybe you might want to rethink your data model.

Similar Messages

  • Hashmap in Hashmap as Key?

    Can anybofy let me know, what could be the possible disastrous outcome of keeping Hashmap in Hashmap as Key?
    Could it lead to inconsistent behaviour?
    If its not a good idea to use Hashmap as key in a Hashmap what other data structure we can use for the same?
    Thanks,
    Amit G.

    Hello Amit,
    I have a question - "Will the contents of the HashMap, which is the key to your second HashMap, change over a period of time.".
    See sample below -
    import java.util.HashMap;
    import java.util.Map;
    public class Foo {
         private Map<Map, String> mainMP = new HashMap<Map, String>();
         private Map<String, String> one = new HashMap<String, String>();
         public static void main(String[] args) {
              Foo f = new Foo();
         Foo() {
              mainMP.put(one, "SomeStr");
              String str = mainMP.get(one);
              System.out.println("First Time : " + str);
              one.put("hello", "where");
              str = mainMP.get(one);
              System.out.println("Second Time : " + str);
    }When you run the program the result will be -
    First Time : SomeStr
    Second Time : null
    The reason is that the hashCode for a Map object depends on its contents. So Map one will have a different hashCode when it is empty and another one when it has the String "hello". So if you add or remove any object from within a Map, the hashCode will change.
    Having a HashMap as a key (which changes over time) to another HashMap is a sure recipe for disaster.
    If you could tell the scenarion where you are using it, maybe I could suggest a different data structure.

  • HashMap of Hashmaps

    Hello, I am trying to make basically a HashMap of HashMaps, where the method gets passed in a URL, and the method creates a HashMap with the URL being the key(because I will only add each URL once and I have a check for that), and the content would be a new HashMap so I can go into that URL and add URL's into the new HashMap(Convaluted I know..) Anyways I have run into a bit of a problem and I dont know how to fix it. Basically when I do this:
         Map<T, Map<T, Map>> graphMap;
         public DemoWebGraph() {
              graphMap= new HashMap<T, Map<T, Map>>();
         }Java wants the Map inside the parameter to have a type. How would I implement something like this or am I looking at it completely wrong?
    Thanks in advance !
    - Niallsc

    niallsc wrote:
    Java wants the Map inside the parameter to have a type.Inside what parameter? And how exactly is anything "inside" a parameter?
    How would I implement something like this or am I looking at it completely wrong?Well for one thing you're attempting to construct an instance of a class that uses Generics without defining the classes of the Type parameters T and Map (bad choice of name, Map, for a Generic type).
    Recommended reading:[http://download-llnw.oracle.com/javase/tutorial/java/generics/index.html]
    db

  • Difference between Map h = new HashMap() and HashMap h1 = new HashMap()

    Hi,
    I am new to Java.I am just confuse that what are the benifits or difference between these two approaches.
    1. Map map = new HashMap();
    2. HashMap hashMap = new HashMap();
    Please reply as soon as possible.
    Thanks
    Sachin

    Well the difference is that one declares the variable "map" as type "Map"
    The second declares the variable as type "HashMap"
    Why would you want to do this?
    Lets say at some point in the future, you decide you want the Map sorted. ie use a TreeMap instead of a HashMap.
    If you have used "HashMap" everywhere in your code, then you need to change all occurences of it to TreeMap.
    However if you just used "Map", the only dependency on "HashMap" is in this one line of code.
    Which do you think would be easier to change?

  • Is a HashMap of HashMaps a bad idea?

    Hi,
    I have a data file to parse through, and when storing the elements of the file, it seems convenient for me to make a HashMap that has a String for a key and a HashMap as a value. Is this a bad idea? I can mess around with ArrayLists and also succeed, but it is not as straightforward as this HashMap idea.
    Thanks.

    my data is kind of structured like this:
    every node has associated neighbors. there are properties for each neighbor. assume that each node has X neighbors. then for the inner HashMap, there would be X entries. the key would be the neighbor, and the value would be the property.
    now, assume that there are Y nodes represented in the file. then there will be Y of these inner HashMaps. so I create the outer HashMap. the key is the node's name and the value is the inner HashMap described above.
    my concern is that this may be wasteful to have all these HashMaps?

  • Hashmap containsKey() method does not appear to work

    Hashmap containsKey() method does not appear to work
    I have an amazingly simple custom class called CalculationKey, with my own amazingly simple custom equals() method. For some reason when I call my containsKey() method on my HashMap it does not use my defined equals method in my defined key class. Do hashmaps have their own tricky way for establishing whether two keys are equal or not?
    THIS IS MY AMAZINGLY SIMPLE CUSTOM KEY CLASS
    private class CalculationKey
    private LongIdentifier repID;
    private LongIdentifier calcID;
    public CalculationKey(LongIdentifier repID, LongIdentifier calcID)
    this.repID = repID;
    this.calcID = calcID;
    public boolean equals(Object o)
    CalculationKey key = (CalculationKey)o;
    if (key.getCalcID().equals(calcID) &&
    key.getRepID().equals(repID))
    return true;
    else
    return false;
    public LongIdentifier getCalcID()
    return calcID;
    public LongIdentifier getRepID()
    return repID;
    THIS IS MY AMAZINGLY SIMPLE CALLS TO MY HASHMAP WHICH ADDS, CHECKS, AND GETS FROM THE HASHMAP.
    private Hashmap calculationResults = new Hashmap();
    public boolean containsCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    if (calculationResults.containsKey(new CalculationKey(repID, calcID)))
    return true;
    else
    return false;
    public Double getCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    return (Double)calculationResults.get(new CalculationKey(repID, calcID));
    public void addCalculationResult(LongIdentifier repID, LongIdentifier calcID, Double value)
    calculationResults.put(new CalculationKey(repID, calcID), value);
    }....cheers

    You can make a trivial implementation to return a
    constant (not recommended)What do you mean by that? Hmm.. I guess you mean that
    you shouldn't use the same constant for all objects?
    But don't see the int value of an (immutable) Integer
    as constant?
    /Kaj
    You can write hashCode to just always return, say, 42. It will be correct because all objects that are equal will have equal hashcodes. Objects that are not equal will also have equal hashcodes, but that's legal--it just causes a performance hit.
    The value is that it's really really simple to implement: public int hashCode() {
        return 42;
    } So you can use it temporarily while you're concentrating on learning other stuff, or during debugging as a way to confirm that the hashCode is not the problem. (Returning a constant from hashcode(), rather than computing a value, is always legal and correct, so if something's behaving wrong, and you replace your hashCode method with the one above, and it still breaks, you know hashCode isn't the problem.)
    The downside is that you're defeating the purpose of hashing, and any non-trival sized map or set is going to have lousy performance.
    For a decent hashCode recipe, look here:
    http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

  • Sorting HashMap based on values

    I need to sort a hashmap based on the values, but also need to keep the keys available for retrieving the values.
    Example:
    key value
    1 c
    2 a
    3 b
    Desired Result
    2 a
    3 b
    1 c
    Thanks for your help.

    You can do this by getting all the Map.ENTRY values in a HashMap object then using a custom Comparator object to sort them by value.
    like this:
    HashMap hashMap =  // your HashMap
    Set entrySet = hashMap.entrySet;
    /* Now add them into a list and use the Collections
    * class to sort them.
    ArrayList list = new ArrayList();
    list.addAll(entrySet);
    Collections.sort(list, yourSpecialComparator);Hope this helps.

  • Vector and Hashmap with the same Content

    Hi Folks
    I have the following Problem, i want to set the same Content in a Vector as in an existing HashMap (both static!)
    These are my trials, both did not work.
    1.)
    static Hashmap hashMap = new HashMap();
    static Vector vector = new Vector(hashMap.values());
    2.)
    public static Vector getElements()
              HashMap cache = hashMap;
              Collection c = cache.values();
              Set set = cache.keySet();
              Iterator it = set.iterator();
              Vector cache1 = new Vector();
              while(it.hasNext())
                   String key = (String)it.next();
                   Element element = (Element)cache.get(key);
                   Element element2 = new Element();
    element2.setAttribut(element.getAttribut())
                   cache1.add(element2);
              cache = cache1;
              return cache;
    Does someone has advice??
    greetings
    Thomas

    Hi,
    why not simply make your method return the local vector (cache1) instead of using additional code ?
    By the way: I'm surprised because the method should return a Vector but instead returns a HashMap. Are you sure your code compiles ?
    Hope this helped,
    Regards.

  • How to use get() method of hashmap in jsp

    Hi,
    Iam using hashMap in action form from which I want to retrieve the value by giving the key in jsp page.
    ex: HashMap m = new HashMap();
    m.add("key", "value");
    String v = m.get("key");
    I want to know how implement m.get("key") in jsp without doing iteration.
    Thanks & Regards,
    Nasrin.N

    Hi
    First of all I would say that there is no "add" method for Hashmap, its put
    secondly try this
    <bean:write property="map_key" name="mapSetterGetter" />

  • I have problems with HashMap

    hello guys
    i have a problems whith this assignment.
    im usunig BlueJ
    its about a library has members and lists of the books available( a catalogue for viewing by members) and of the copies of
    these (for stock control purposes).
    information of a book (title, author, and ISBN), the title is a unique identifier.
    a book may have several copies, each with a unique stock number (an integer). a book may have no copies (if, for
    example, it has been added to the catalogue, but copies havent yet arrived.
    the library most be able to:
    - add a book to the catalogue for example when its newly published.
    - add a copy of a book to its stock when the library receives this item.
    - obtain a list of copies of a book, given its title.
    - obtain a String representation of the list of copies of a book, given its title; this should just be the title
    and list of stock numbers, for examble :( title, copies: 2000, 2001, 2002).
    now i cant make the HashMap for the stock items,
    is there anything wrong i have made or any suggestions to help me to continue my work?
    the two classes i have made so far:
    public class books
        private String title;
        private String author;
        private String ISBN;
        private int quantity;
        private int stockNumber;
        public books(String title, String author, String ISBN)
            this.title = title;
            this.author = author;
            this.ISBN = ISBN;
            //stock number satrts from 2000
            stockNumber = 1999;
        public int addquntity (int amount)
                quantity = quantity + amount;
                return quantity;
        // chang the quantity when costumer borrows a book from the library
        public int getBorowed()
            if(quantity > 0){
              quantity --;
            else{
                System.out.print("sorry the book is not avalible, try again later");
                return quantity;
        // chang the quantity when costumer rturnes a book to the library
        public void deliverBookBack()
            quantity++;
        public String toString()
            return title + " by " + author + ". ISBN = " + ISBN ;
        // change the stock number after adding any book to the library
        public int autoStockNumber()
            stockNumber ++;
            return stockNumber;
        public int getStockNumber()
            return  stockNumber;
    }======================================================
    import java.util.ArrayList;
    import java.util.HashMap;
    public class library
        private ArrayList<books> book;
        private ArrayList<members> member;
      // i coudnt make the HashMap here.
        private HashMap<books , books> stock;   
        public library ()
            book = new ArrayList<books>();
            member = new ArrayList<members>();
            stock = new HashMap<books, books>();       
        // to add a book to the catalogue, for example when its newly published (the book information)
        public void newBook(books bk)
            book.add(bk);
        public void TheStateOfTheLibrary()
            //print the library name and address
            System.out.println("BlueJ Library: 10 College Lane, AL10 9BL");
            // print list of the books (title, author, ISBN)
            System.out.println("Catalogue :");
            for (books bk : book){
                System.out.println(bk);
            System.out.println("");
             * print stock list to show all stocks in the library
             *it should show:
             *stock number, books name, by : thuthor. ISBN
            System.out.println("Stock List:");
            System.out.println("");
            System.out.println("Membership List:");       
            for (members memb : member){
                System.out.println(memb);
        public void addMember(members memb)
            member.add(memb);
        // to add a copy of a book to it's stock, when the library receives this item.
        public void addBookToStock(books sn)
           // i coudnt make it
    }thank you

    actually im new in java and i dont really understand the HashMap.A HashMap is like an array except the index values of the array aren't integers. If you declare an array like this:
    int[] nums = new int[10];
    the index values of the array are the integers 0-9. To store something in the array, you do something like this:
    nums[0] = 3;
    0 is the index value and at that index position in the array is the integer 3.
    With a HashMap, you can use index values other than integers for your array. For instance, you can use Strings:
    index value           value stored at that index position in the array
    "John"                           "232-0416"
    "Sally"                          "451-0091"To add an index value to the map and store a value at that index position, you would do this:
    myMap.put("Jane", "456-7654");
    To get the telephone number at index position "John", you would do this:
    myMap.get("John");
    However, you have to do a little more work on the object returned by get(). When you add objects, like String objects, to one of java's collections, they are automatically converted to type Object first and then added to the collection. Then, when you retrieve objects from a collection, they are returned as type Object, so you need to cast them to their original type:
    String result = (String) myMap.get("John");
    That statement gets you whatever is stored at index position "John" in the array, which happens to be the String "232-0416". You don't have to make that cast in java 1.5 when you use generics, which is what you are doing.
    One last point: in HashMap lingo, the index values in the array are called "keys".
    i have an error " cannot find symbol- method put(int,books)You defined your HashMap like this:
    private HashMap<books , books> stock;
    That tells java that you are going to be using 'books' objects for the index values of the array, and that the values stored at those index positions will be 'books' objects. But here:
    public void addBookToStock(Books sn, Books b)
            int key = sn.getStockNumber();
            stock.put(key,  b);       // the error is in this line.
    }you are trying to use an int as the index value of the array. Since you told java you would be using "books" as index values, it produces an error.
    You should also rename your Books class to "Book". A Book object does not consist of several books--it represents only one book. If you had a collection containing a bunch of Book objects, then it would make sense to name the collection "Books".

  • Hashmap within a Hashmap?  Or better solution?

    I might be approaching this all wrong, but I think I want to have a group of nested hashmaps. I'm trying to build an auction house. When someone comes with a new product category, I want create a hashtable for that product category so hashmap allows me to label the category and put in the product as object. then, i want another level of hashtable to map individual product with the bids it receives ($ amounts). and, finally, i want to be able to label each bid by an id token, so, if the bidder comes back, i can then cancel or amend their bid. I was thinking of using an ArrayList to contain the bids for two reasons: (1) I want to order the bids so that I can respond to them on a first come first served basis and (2) I figured I could just keep track of the bid's price and search through the ArrayList for the id to modify it.
    I know the following won't work, but am I anywhere close? And, also, how do I deal with determining whether a product category hash has already been created (or a bid price hash) or whether i need to instantiate one? Thanks so much in advance!!!
         private static Map<String, Map<Double, ArrayList<String>>> productCategory;
         private static Map<Double, ArrayList<String>> bids; // double used for the bids and array list of strings is for the id tokens
         public static void main (String[] args) {
              productCategory = new HashMap<String, HashMap <Double, ArrayList<String>>>;
              bids = new HashMap<Double, ArrayList<String>>;

    Hmmm... I suppose you could use hashmaps to "map" these relationships, but that doesn't make it a good idea.
    There is no need to use a "dynamic" datastructure like a Map to define the relationships you describe. Nesting Maps allows you to model a "tree" of arbitrary depth and complexity (like a file-system directory tree), but in this case "the complete set of allowable relationships between types" is know up-front... note that's between types, not individual instances... so this is a classical "static model" which (funnily enough) should be modeled "statically".
    SO... I'd be inclined to model all these relationships as has-a relationships, using simple attribute fields (some of which will be lists).... atleast for the first cut.... later you might decide that there really are subtypes of things (like FloorBid, PhoneBid, or OnlineBid) and you would "refine" the model at that stage.
    SO.... I guess I'd start with: An Auction has a Product and a list of Bids. You add a Product to the list, then create an Auction on that product, advertise, and hopefully recieve some Bids. At the completion of the auction some moneyis exchanged for the goods... and the Product, its Auction, and it's bids are either deleted; or (more likely) archived off to a warehouse of historical auction records.
    HashMaps are for when you don't/can't know ALL the type-relationships upfront. What you where thinking of doing constitutes abuse (that's too strong a term, but can't think of "the right word") of there dynamic modeling ability.
    My advise is "get something down". Getting a "first draft" down is the hard bit... it's the bit where even seasoned IT pro's sometimes suffer "writers block".
    HTH.
    Cheers. Keith.
    Edited by: corlettk on 20/09/2009 13:37 ~~ Clearer.

  • Order by the names in hashMaps which are contained within a collection

    Hi All,
    Is there a way to order by the names in hashMaps which are contained within a collection?
    Collection-->hmp1(nrPerson1, nameB);
    hmp2(nrPerson2, nameC);
    hmp3(nrPerson3, nameA);
    Now what i need to display is (nrPerson3,nameA), (nrPerson1,nameB), (nrPerson2, nameC)...
    Any suggestion will be greatly appreciated!
    Shuaibing

    I just set the TreeSet with the values as you suggested, but the results seems to the same as usual, Can you check the following codes? I think I need have to give a initial parameter for the TreeSet constructor, but I do not know how to write the Comparator.
    public String getIntermediaryCO(){
    Contact contact=new Contact();
              Collection colnNrContactsInterCo=contact.getAllIntermediaryCompany();
              //test
              TreeSet treeSet=new TreeSet();
              HashMap hmpForOrder=new HashMap();
              if(colnNrContactsInterCo!=null && !colnNrContactsInterCo.isEmpty()){
                   Iterator iter=colnNrContactsInterCo.iterator();
                   while(iter.hasNext()){
                           HashMap hmp=(HashMap)iter.next();
                           hmpForOrder.put(hmp.get("name"),hmp.get("nrContact"));
              treeSet.add(hmpForOrder.keySet());
              //print the ordered, unique set
            Iterator iterator = treeSet.iterator();
            while( iterator.hasNext() ) {           
                System.out.println( "the list of sorted intermediary companies' names="+iterator.next() );
              //test
    public Collection getAllIntermediaryCompany(){
               Collection colnContacts=new ArrayList();
               ContactCov contactCov=new ContactCov();
             try{
                    String sql="SELECT DISTINCT NR_CONTACT from CONTACT_TYPE where CD_CONTACT_TYPE=5";
                    jdbc = new JDBCConnection("1");
                    rs=jdbc.executeQuery(sql);
                    if(rs!=null){
                         while(rs.next()){
                                   String nrContact=rs.getString("NR_CONTACT");
                                   VOContact voContact=contactCov.getContactByNrContact(nrContact);
                                   if(voContact!=null){
                                        HashMap hmp=new HashMap();
                                        hmp.put("name",voContact.getName());
                                        hmp.put("nrContact",nrContact);
                                        colnContacts.add(hmp);
                  }catch(Exception e){
                      logger.error(e.toString());
                   }finally{
                       try{
                            if(rs!=null)rs.close();
                            if(jdbc!=null)jdbc.close();
                       }catch(Exception e){}
               return colnContacts;     
            }     

  • Vector is way faster than HashMap (why?)

    I thought that HashMap would be faster than Vector (in adding stuff) ... could anyone explain to me why there was such a HUGE difference??
    here's the code I used:
    public class SpeedTest
    public static void main(String[] args)
       final int max=1000001;
       Integer[] arrayzinho = new Integer[max];
       Arrays.fill(arrayzinho,0,max,new Integer(1));
       Vector jota = new Vector(max,max);
       HashMap ele = new HashMap(max,1);
       System.out.println("Adicionando " + (max-1) + " elementos ao array...");
       long tempo = System.currentTimeMillis();
       for(int i=0;i<max;i++)
          arrayzinho[i] = new Integer(i);
       System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    //ops
       System.out.println("Adicionando " + (max-1) + " elementos ao Vector...");
       tempo = System.currentTimeMillis();
       for(int i=0;i<max;i++)
          jota.add(arrayzinho);
    System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    //ops
    System.out.println("Adicionando " + (max-1) + " elementos ao HashMap...");
    tempo = System.currentTimeMillis();
    for(int i=0;i<max;i++)
    ele.put(arrayzinho[i],arrayzinho[i]);
    System.out.println("A opera??o demorou " + ((System.currentTimeMillis()-tempo)) + " msecs.");
    Of course, when adding to HashMap, two values are entered instead of just the one added in the Vector... But, even doubling the time Vector used, the difference is huge!
    here's some output I've got:
    1:
    Adicionando 1000000 elementos ao array...
    A opera??o demorou 4500 msecs.
    Adicionando 1000000 elementos ao Vector...
    A opera??o demorou 469 msecs.
    Adicionando 1000000 elementos ao HashMap...
    A opera??o demorou 7906 msecs.
    2:
    Adicionando 1000000 elementos ao array...
    A opera??o demorou 4485 msecs.
    Adicionando 1000000 elementos ao Vector...
    A opera??o demorou 484 msecs.
    Adicionando 1000000 elementos ao HashMap...
    A opera??o demorou 7891 msecs.
    and so on, the results are almost the same everytime it's run. Does anyone know why?

    Note: This only times the for loop and insert into each one... not the lookup time and array stuff of the original..
    Test One:
    Uninitialized capacity for Vector and HashMap
    import java.util.*;
    public class SpeedTest
        public static void main(String[] args)
            final int max = 1000001;
            Vector jota = new Vector(); // new Vector(max,max);
            HashMap ele = new HashMap(); // new HashMap(max,1);
            Integer a = new Integer(1);
            long tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                jota.add(a);
            long done = System.currentTimeMillis();
            System.out.println("Vector Time " + (done - tempo) + " msecs.");
            tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                ele.put(a, a);
            done = System.currentTimeMillis();
            System.out.println("Map Time " + (done-tempo) + " msecs.");
        } // main
    } // SpeedTestAdministrator@WACO //c
    $ java SpeedTest
    Vector Time 331 msecs.
    Map Time 90 msecs.
    Test Two:
    Initialize the Vector and HashMap capacity
    import java.util.*;
    public class SpeedTest
        public static void main(String[] args)
            final int max = 1000001;
            Vector jota = new Vector(max,max);
            HashMap ele = new HashMap(max,1);
            Integer a = new Integer(1);
            long tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                jota.add(a);
            long done = System.currentTimeMillis();
            System.out.println("Vector Time " + (done - tempo) + " msecs.");
            tempo = System.currentTimeMillis();
            for (int i = 0; i < max; ++i)
                ele.put(a, a);
            done = System.currentTimeMillis();
            System.out.println("Map Time " + (done-tempo) + " msecs.");
        } // main
    } // SpeedTestAdministrator@WACO //c
    $ java SpeedTest
    Vector Time 60 msecs.
    Map Time 90 msecs.
    We see that IF you know the capacity of the vector before its usage, it is BEST to create one of the needed capacity...

  • Static HashMap is created many times

    we are developing robots with friends for robocode, a game in which robots fights that you write in java, probably you know it.
    we want to keep information of robots in a HashMap. when our robots detect an enemy robot they will add that enemy as an object to the hashmap.
    each of the robots are a thread =>that means multiple threads will add objects to the same hashmap. so hashmap will be static and the method will be synchronized. our problem is about the static part. there have to be one hashmap and every thread(robot) must use it but each thread(robot) use a different hashmap.
    how will we be able to use one unique hashmap for all threads.
    Message was edited by:
    elix

    Well, the first thing you need to realize is that you can't have more than one thread accessing a HashMap simultaneously. That will break things. You will probably need to get a synchronized map by calling Collections.synchronizedMap.
    As for your central HashMap... just declare it as static.
    public class SomeClass {
        public static final Map<SomeKey,SomeValue> robotMap = Collections.synchronizedMap(new HashMap<SomeKey,SomeValue>());
    public class SomeOtherClass {
        public void putSomethingInTheRobotMap(SomeKey k, SomeValue v) {
            SomeClass.robotMap.put(k, v);
    }

  • Serialization giving probem with HashMap

    Hi,
    I am creating a new document and could serialize it without fail.
    But if I add the created document to the HashMap. and then get the document from hashMap and try to serialize, OutputFormat throws NullPointerException,
    Here's the exception message---
    java.lang.NullPointerException
            at org.apache.xml.serialize.OutputFormat.whichMethod(Unknown Source)
            at org.apache.xml.serialize.OutputFormat.<init>(Unknown Source)*/
    Here's the code I am using--->
    HashMap documentsMap = new HashMap();
    Document doc= new DocumentImpl();
    Element root = doc.createElement("person");     // Create Root Element
    Element item = doc.createElement("name");       // Create element
    item.appendChild( doc.createTextNode("Jeff") );
    root.appendChild( item );       // Attach another Element - 
    doc.appendChild( root );        // Add Root to Document
    //add to the HashMap....
    documentsMap.put("node1",doc );
      try
       Iterator iterator = documentsMap.entrySet().iterator();
       while (iterator.hasNext() )
          Object key = iterator.next();
          doc= (Document)taxonomyNodesMap.get(key);
          OutputFormat format  = new OutputFormat( doc );   //Serialize DOM
          StringWriter  stringOut = new StringWriter();        //Writer will be a  
         XMLSerializer    serial = new XMLSerializer( stringOut, format );
        serial.asDOMSerializer();                            // As a DOM Serializer
        serial.serialize( doc.getDocumentElement());
      }catch......
    Any help will be greatly appreciated..
    Regards,
    Peter

    You have to use
    Iterator iterator = documentsMap.keySet().iterator();to get an iterator over all KEYS in your Hashmap.
    Cheers,
    Torsten

Maybe you are looking for