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

Similar Messages

  • HT1657 i received an email about a probem with a movie rental

    i received an email about a probem with a movie rental and was given 1 rental credit. but i have no idea how to redeem that credit. i can see that i have it in my account info and at the the top right of the screen next to my account name but cant do anything with it. thanks

    You can't, directly on your phone. This is not supported on the iPhone. You need to get the song into your iTunes library, then sync it to your phone.

  • Urgent:Issue with HashMap while creating session in Java Embedding Activity

    Hi,
    I am unable to createsession() with the values from HashMap. following is the code in JEA
    IAgileSession m_session=null;
              IAdmin admin = null;
              IAgileClass cls = null;
              IAutoNumber[] numSources;
              String nextAutoNumber = null;
    try {
                   HashMap params = new HashMap();
                   params.put(AgileSessionFactory.USERNAME, "*********");
                   params.put(AgileSessionFactory.PASSWORD, "*******");
    int s= params.size();
    String y= (String)params.get(AgileSessionFactory.USERNAME);
    String z= (String)params.get(AgileSessionFactory.PASSWORD);
    addAuditTrailEntry("UserName " +y);  
    addAuditTrailEntry("Password " +z);  
    addAuditTrailEntry("Size is " +s);   
                   AgileSessionFactory instance = AgileSessionFactory.getInstance("******************************");
    addAuditTrailEntry("After instance object" +instance);
    m_session = instance.createSession(params);
    addAuditTrailEntry("" +m_session);
    addAuditTrailEntry("After instance object_Session");
                   admin = m_session.getAdminInstance();
                   cls = admin.getAgileClass( "ProblemReport" );
                   IServiceRequest psr = (IServiceRequest)m_session.createObject( "ProblemReport", "PR-9989909");     
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   m_session.close();
    In the above code it is working perfectly up to AgilSessionFactory instance, but after that when I am printing m_session ( i.e. addAuditTrailEntry("" +m_session);) it is returning null values instead of some session ID. I am also able to print AgilesessionFactoy instance ID correctly inside JEA, but only problem is with m_session. I tried with the same code in java client and it is working perfectly. Please some one help me in this issue.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi,
    I am unable to createsession() with the values from HashMap. following is the code in JEA
    IAgileSession m_session=null;
              IAdmin admin = null;
              IAgileClass cls = null;
              IAutoNumber[] numSources;
              String nextAutoNumber = null;
    try {
                   HashMap params = new HashMap();
                   params.put(AgileSessionFactory.USERNAME, "*********");
                   params.put(AgileSessionFactory.PASSWORD, "*******");
    int s= params.size();
    String y= (String)params.get(AgileSessionFactory.USERNAME);
    String z= (String)params.get(AgileSessionFactory.PASSWORD);
    addAuditTrailEntry("UserName " +y);  
    addAuditTrailEntry("Password " +z);  
    addAuditTrailEntry("Size is " +s);   
                   AgileSessionFactory instance = AgileSessionFactory.getInstance("******************************");
    addAuditTrailEntry("After instance object" +instance);
    m_session = instance.createSession(params);
    addAuditTrailEntry("" +m_session);
    addAuditTrailEntry("After instance object_Session");
                   admin = m_session.getAdminInstance();
                   cls = admin.getAgileClass( "ProblemReport" );
                   IServiceRequest psr = (IServiceRequest)m_session.createObject( "ProblemReport", "PR-9989909");     
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   m_session.close();
    In the above code it is working perfectly up to AgilSessionFactory instance, but after that when I am printing m_session ( i.e. addAuditTrailEntry("" +m_session);) it is returning null values instead of some session ID. I am also able to print AgilesessionFactoy instance ID correctly inside JEA, but only problem is with m_session. I tried with the same code in java client and it is working perfectly. Please some one help me in this issue.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • StackOverflowError with HashMap

    We are experiencing a problem where we get a StackOverflowError after recursing too many times in a HashMap. It's quite a deep recursion, from what I can tell, over 1024 times.
    The odd thing is that we are only getting this error on a Windows machine. We tested it on a Linux machine and it works fine with no errors.
    Does anyone know of a problem like this on a Window machine, and how to fix it?
    Thanks!

    Here's the stack trace:
    Parsing "test.xml"... Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap.containsKey(Unknown Source)
    at java.util.HashSet.contains(Unknown Source)
    at our.package.XRef.remove(XRef.java:410)
    at our.package.XRef.access$000(XRef.java:16)
    at our.package.XRef$Entry.setObject(XRef.java:112)
    at our.package.XRef.addObject(XRef.java:297)
    at our.package.XRef.mark(XRef.java:191)
    at our.package.XRef.mark(XRef.java:199)
    at our.package.XRef.mark(XRef.java:199)
    at our.package.XRef.mark(XRef.java:199)
    at our.package.XRef.mark(XRef.java:199)
    at our.package.XRef.mark(XRef.java:199)
    at our.package.XRef.mark(XRef.java:199)
    etc, etc, for about 1000 lines....
    If I put a try... except block in the XRef.remove method, I can't even catch the error, which is extremely odd. Which also means the error must be coming from somewhere else, but I don't know where.
    I'm running with the lastest release of the JVM 1.5, on a Windows XP P4 with over 700MB RAM.

  • SelectMany checkbox value-binded with HashMap String,ArrayList

    Hello,
    Someone can help me please?
    Im trying to create a page with a lot of HtmlSelectManyCheckbox, and i need to value-bind then to the same Object in my BackingBean.
    First i attemped to bind all HtmlSelectManyCheckbox with a single ArrayList, but only the last SelectMany had their values inserted on the ArrayList...
    So, now im trying to bind all the HtmlSelectManyCheckbox with a HashMap<String,ArrayList>, because i would have just one object and for each entry I would have the checkboxes that were cheked in a single HtmlSelectManyCheckbox.
    Now my question: there is a way to make this work?
    my code example
    Backing bean
    private HashMap<String, ArrayList> respostaMatrizCheck = new HashMap<String, ArrayList>();
         public HashMap<String, ArrayList> getRespostaMatrizCheck() {
              return respostaMatrizCheck;
         public void setRespostaMatrizCheck(HashMap<String, ArrayList> respostaMatrizCheck) {
              this.respostaMatrizCheck = respostaMatrizCheck;and the bindings
    <h:selectManyCheckbox value="#{backingBean.respostaMatrizCheck['1'] }">
    <h:selectManyCheckbox value="#{backingBean.respostaMatrizCheck['2'] }">And the error message given when i tryed this is the following:
    javax.servlet.ServletException: ValueBinding for UISelectMany must be of type List or Array
    Any help would be welcome.
    Thanks,
    Ferry

    Has anybody solved a problem like this? I am facing the same problem and no response helped me so far.
    Here is the web code:
    <h:selectManyCheckbox value="#{processor.languages.languages1}">
         <f:converter converterId="languageConverter" />
         <f:selectItems value="#{categoryController.allLanguagesAsSelectItems}" />
    </h:selectManyCheckbox>My backing bean "processor" looks like this:
         public Map<String, List<MyObject>> getLanguages() {
              return languagesMap;
         }(The backing bean has no "setLanguages()-method" since I did not need any with Map<String, String> for example.)
    The converter I use creates a "MyObject" instance in its "getAsObject" conversion method.
    I think everything should be okay then but the exception I get after submitting the page is:
    java.lang.IllegalArgumentException: ValueBinding for UISelectMany must be of type List or Array
         org.apache.myfaces.shared_impl.renderkit._SharedRendererUtils.getConvertedUISelectManyValue(_SharedRendererUtils.java:191)
         org.apache.myfaces.shared_impl.renderkit.RendererUtils.getConvertedUISelectManyValue(RendererUtils.java:630)
         org.apache.myfaces.shared_impl.renderkit.html.HtmlCheckboxRendererBase.getConvertedValue(HtmlCheckboxRendererBase.java:308)
         javax.faces.component.UISelectMany.getConvertedValue(UISelectMany.java:308)
         javax.faces.component.UIInput.validate(UIInput.java:350)
    .....Edited by: rapthor on Oct 31, 2007 6:39 AM

  • UISelectMany - Conversion error with HashMap Property

    Hi,
    I have a Backing Bean with a HashMap Property.
    public HashMap getItem()
    public void setItem(HashMap map)
    so I bind a Value of an UIInputText Component like that:
    <h:inputText id="txtname" value="#{MyBean.item['myKey']}" />
    this works pretty well.
    But when I try to do the same with an <h:selectManyCheckbox> Component I got a "Conversion Error".
    For what reason? I expected an Array or List Object.
    Thanks for help
    Ralph

    I solved the problem by creating a custom converter, which checks if the current valueBinding is null.
    If so, it replace the valueBinding with an empty ArrayList().
    public class MultiValueConverter implements Converter {
         public final static String CONVERTER_ID = "org.imixs.workflow.j2ee.faces.MultiValueConverter";
         public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
    // no changes
    return value;
         public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
    // Check if current value Binding is bind to an null-Object
    javax.faces.el.ValueBinding valueBinding=component.getValueBinding("value");
    if (valueBinding!=null && valueBinding.getValue(context)==null) {
    // replace binding with empty ArrayList
    valueBinding.setValue(context,new ArrayList());
    // no changes
    return value.toString();
    you can find the full code under www.imixs.org (an open source project for a EJB based workflow engine)

  • How to Serialize/Deserialize Beans with Web Services using DII client

    Dear All;
    I had developed a web serivce by Oracle JDeveloper [J2EE 1.4 (JAX-RPC)] and trying to invoke methods within through DII client using Apache Axis 1.
    The Beans I am using are structured as follows:
    public class InBean {
    public InBean() {
    private int x;
    private float y;
    public setters/getters for x
    public setters/getters for y
    public class OutBean {
    public OutBean() {
    private String inString;
    private String outString;
    public setters/getters for inString
    public setters/getters for outString
    The (InBean) is used as method input and the (OutBean) is used as method output.
    The problems I am facing are as follows:
    [1] How to serialize/desrialize the Beans as they are not registered with Apache Axis 1?
    [2] How to invoke the Beans using Dynamic client DII and not classic proxy and Stubs?
    [3] How to create the Beans using WSD2Java of the Apache Axis 1 ?
    In case you have any helping URL's, Book names or sample code, please attach as they will be very helpful.
    Thanks alot for the help.-----
    Best Regards,
    Ahmed M. Abbas

    You will find some working code at :
    http://ksoap.objectweb.org/software/downloads/index.html
    It's code that use kSOAP and kXML implementations ....
    If you will also find some useful information here :
    http://developers.sun.com/techtopics/mobility/apis/articles/wsa/
    http://www-106.ibm.com/developerworks/wireless/library/wi-jsr/
    http://www-106.ibm.com/developerworks/wireless/library/wi-xmlparse/
    Regards.

  • Generate Serializable data types with WSDLC

    Hello everyone,
    I'll was pretending to send a through a JMS ObjectMessage a type generated from WSDL with the wsdlc ant task. Unfortunately the generated types are not serializable and so I'm unable to send the message. It's really ackward to manualy change all of them so I would like to know if it's possible to instruct wsdlc to generate serializable data types. I'm using Weblogic 11gR1PS1. If it's not possible what do you recommend ?
    Currently the tasks are configured like this:
    <taskdef name="wsdlc" classpathref="weblogic.classpath" classname="weblogic.wsee.tools.anttasks.WsdlcTask" />
    <wsdlc srcWsdl="ejbModule/META-INF/wsdl/DataCatalog.wsdl" destJwsDir="gen" destImplDir="gen" packageName="br.com.allwayx.schema" type="JAXWS">
    Obs: I noticed that If I use a binding element inside the task passing any xjb file the wsdlc task generates a pair of Entity interface - EntityImpl implementation class. It stays like this:
    <wsdlc srcWsdl="ejbModule/META-INF/wsdl/DataCatalog.wsdl" destJwsDir="gen" destImplDir="gen" packageName="br.com.allwayx.schema" type="JAXWS">
                   <binding dir="${binding.declaration.dir}" includes="${binding.declaration.file}" />
    </wsdlc>
    Still I would like to keep the old way, without the binding element which generates just a concrete class for each element. Maybe this is a bug?
    Thank you !
    Edited by: Lupan on 28/04/2010 13:13

    Hi Lupan,
    Currently I believe there is no way to instruct WSDLC task to generate the Serializable data types.
    There was already a BUG opened with BEA for WLS -9.0 following are the BUG details:
    http://download.oracle.com/docs/cd/E13222_01/wls/docs100/issues/known_resolved.html
    CR228385
    Description:
    The Web Service Description Language (WSDL) compiler does not generate serializable data types, so data cannot be passed to remote EJBs or stored in a JMS destination.
    You should contact the Oracle Weblogic Support to get the current status of the BUG.
    Thanks,
    Sandeep

  • Would like some help with hashmaps please :)

    Map<Integer, Double> probabilities = new HashMap<Integer, Double>();When i try to use the above code in a foreach loop
    for (Map.Entry<Integer, Double> entry : probabilities)i get this error
    Foreach not applicable to expressionCould anyone please enlighten me on what is wrong with that and maybe suggest another way of running through the HashMap.
    THANKS!

    for (Map.Entry<Integer, Double> entry : probabilities.entrySet())

  • 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".

  • Help needed with hashmap

    i have a class and declared some varaibales. In another class i am setting values for those variables.
    can i get the values of those variables into hashmap and iterate over those values
    if yes, can somebody pls tell me how to do that...
    for ex...
    class abc
    string x;
    string y;
    public String getx() {
    return x;
    public void setx(String x) {
    this.x = x;
    public String gety() {
    return y;
    public void sety(String y) {
    this.y = y;
    in another class
    class ABC
    abc a = new abc();
    a.setx("123")
    a.sety("xyz")
    now, i want to retreive those values(123 and xyz) and iterate over them ( in a hashmap) ,i.e convert them into objects and return them...
    pls tell me how to do that...
    thanks

    Mani_V wrote:
    can somebody explain with a sample code..pls1 Copy the link for the tutorial. Paste it into your browser.
    2 On the tutorial page, click on Interfaces
    3 On the Interfaces page, click on The Map Interface
    4 Just a little ways down the page, a HashMap example with explanation.

  • Help with HashMap!!!

    Hi all,
    My program reads the data from the external file called: "long.txt" which consists of a million records...
    The file is loaded into a list called: "HashMap list" and also store the keys into a separate array. Search is done in HashMap for all the key in the array or also known as an exhaustive search.
    I have the files: "long.txt", "HashMapTestnew.java" and "MyData.java" in the same directory called: "tmp"...
    Everything looks okay but when I try to compile this, I get the following error...
    HashMapTestnew.java:38: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTestnew
    MyData md = new MyData( sKey, Integer.parseInt(sVal) );
    ^
    HashMapTestnew.java:38: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTestnew
    MyData md = new MyData( sKey, Integer.parseInt(sVal) );
    ^
    HashMapTestnew.java:55: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTestnew
    MyData md;
    ^
    HashMapTestnew.java:66: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTestnew
    md = (MyData) me.getValue();
    ^
    4 errors
    Tool completed with exit code 1
    import java.util.*;
    import java.io.*;
    public class HashMapTestnew
    public static HashMap getMapList()
         String MyData;
         Int sKey;
    String strLine;
    HashMap hm = new HashMap();
    try
    BufferedReader fBR = new BufferedReader( new FileReader("long.txt") );
    while ( fBR.ready() )
    strLine = fBR.readLine();
    if (strLine != null)
    StringTokenizer st = new StringTokenizer(strLine, "\t");
    String sKey = st.nextToken();
    String sVal = st.nextToken();
    MyData md = new MyData( sKey, Integer.parseInt(sVal) );
    hm.put(sKey, md);
    fBR.close();
    catch (IOException ioe)
    System.out.println("I/O Trouble ...");
    return hm;
    public static void showMapList(HashMap hashMap, int n)
    String strVal;
    String strNdx;
    MyData md;
    System.out.println("\nHashMap List (first 10 records):");
    Map.Entry me;
    Set shm = hashMap.entrySet();
    Iterator j = shm.iterator();
    int i = 0;
    while (j.hasNext() && (i++)< n)
    me = (Map.Entry) j.next();
    strVal = (String) me.getKey();
    md = (MyData) me.getValue();
    System.out.println(i + ": " + md.getVal() + "\t" + md.getNdx() );
    public static String[] getKeys(HashMap hashMap)
    String[] key = new String[hashMap.size()];
    Map.Entry me;
    Set shm = hashMap.entrySet();
    Iterator j = shm.iterator();
    int i = 0;
    while (j.hasNext())
    me = (Map.Entry) j.next();
    key[i] = (String) me.getKey();
    i++;
    return key;
    public static void searchMapList(HashMap hashMap, String[] key)
    int i,n=0;
    System.out.println("Search Started:");
    long tim1 = System.currentTimeMillis();
    for (i=0; i<key.length; i++)
    if (hashMap.containsKey(key))
    n++;
    long tim2 = System.currentTimeMillis();
    System.out.println("Search Ended After " + (tim2-tim1) + " miliseconds.");
    System.out.println("Searched for " + key.length + " keys.");
    System.out.println("Found " + n + " keys.");
    public static void main(String[] arg)
    HashMap hashMap = getMapList(); // Create the hash map list
    showMapList(hashMap, 10); // Display part of the hash map list
    String[] searchKey = getKeys(hashMap); // an array of all search keys
    searchMapList(hashMap, searchKey); // Search for all existing keys in the list
    Can anybody help me with this?
    I'm new to Java... What does the error message: "cannot resolve symbol
    symbol : class MyData" mean???
    P.S. When I compiled the file "MyData.java", it compiles without any error...
    Thanks,
    Lilian

    I moved the 3 files ("MyData.java", "long txt" and "HashMapTest.java") to a directory called "MyData" as well as added the code: "package MyData;"
    before the codes:
    import java.util.*;
    import java.io.*;
    just to see if it would make any difference but I still got the following error messages:
    C:\WINDOWS\DESKTOP\MyData\HashMapTest.java:38: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTest
    MyData md = new MyData( sKey, Integer.parseInt(sVal) );
    ^
    C:\WINDOWS\DESKTOP\MyData\HashMapTest.java:38: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTest
    MyData md = new MyData( sKey, Integer.parseInt(sVal) );
    ^
    C:\WINDOWS\DESKTOP\MyData\HashMapTest.java:55: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTest
    MyData md;
    ^
    C:\WINDOWS\DESKTOP\MyData\HashMapTest.java:66: cannot resolve symbol
    symbol : class MyData
    location: class MyData.HashMapTest
    md = (MyData) me.getValue();
    ^
    4 errors
    Tool completed with exit code 1
    By the way, I'm compiling the java program using a Textpad editor and selecting Tools -->> Compile Java...
    Let me know if you have any questions...
    Thanks,
    Lilian
    location: class MyData.HashMapTestnewThis says that you have declared your HashMapTestnew
    class to be in package MyData.
    I have the files: "long.txt", "HashMapTestnew.java"and "MyData.java" in the same directory called:
    "tmp"...
    If you want HashMapTestnew to be in package MyData,
    then it should have been in a directory called MyData.
    But having a class with the same name as a package is
    very confusing, so I don't think you should do that.
    In fact, since you are new to Java I don't think you
    u should use packages at all until you can compile
    non-packaged classes correctly.
    I'm surprised I don't see the line "package MyData" at
    the top of the code you posted. But then I'm not
    surprised, because since your class isn't in the right
    directory for that package, you should have got
    different error messages. What exactly did you type
    at the command line to compile the class?

  • Help with HashMap and Collections

    Hey everyone,
    I am currently writing a program that makes use of HashMap, which I am not at all familiar with. I looked it up in some books and some websites, but it seems everyone does something different every time so I need some guidance. My program is to take Inventory Item objects that have an name and an inventory number and store them in a HashMap. Originally I had them stored in an Array but now it's gonna be in a HashMap. This also uses some Java GUI elements so bear with me.
    Ok, first here is my code for my Item object:
    public class Item{
        private String number;
        private String name;
        public Item(String number, String name) {
              this.number = number;
              this.name = name;
          @Override
          public String toString() {
              return "#"+number+"  N:"+name;
    }And this is what I got so far for my Inventory GUI:
    import java.util.HashMap;
    import java.util.Iterator;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JScrollPane;
    public class InventoryGUI {
         //private static Item[] item = new Item[10];
         HashMap hash = new HashMap();
         private static int count = 0;
         public static void main(String[] args) {
              JFrame gui = new JFrame("Project 2 GUI");
              gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              JPanel inputPanel = new JPanel();
              inputPanel.setLayout(new GridLayout(5,2));
              inputPanel.add(new Label("Inventory Number"));
              final JTextField numberField = new JTextField(15);
              inputPanel.add(numberField);
              inputPanel.add(new Label("Name"));
              final JTextField nameField = new JTextField(15);
              inputPanel.add(nameField);
              gui.add(inputPanel, BorderLayout.NORTH);
              final DefaultListModel dfl = new DefaultListModel();
              JList jl = new JList(dfl);
              JScrollPane jsp = new JScrollPane(jl);
              gui.add(jsp);
              JPanel southPanel = new JPanel();
              southPanel.setLayout(new GridLayout(2,1));
              final JTextField errorMsg = new JTextField();
              errorMsg.setEditable(false);
              southPanel.add(errorMsg);
              JPanel buttonPanel = new JPanel();
              southPanel.add(buttonPanel);
              JButton addButton = new JButton("Add");
              addButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        String number = numberField.getText();
                          numberField.setText("");
                         String name = nameField.getText();
                          nameField.setText("");
                               hash.put(number, name);
                               count++;
              buttonPanel.add(addButton);
              JButton deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(deleteButton);
              JButton findButton = new JButton("Find");
              findButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                        String temp = hashMap.get(number);
                              dfl.addElement(temp);
              buttonPanel.add(findButton);
              JButton showButton = new JButton("Show");
              showButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                          for (Item p : item) {
                              dfl.addElement(p);
              buttonPanel.add(showButton);
              JButton saveButton = new JButton("Save");
              saveButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(saveButton);
              JButton restoreButton = new JButton("Restore");
              restoreButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(restoreButton);
              JButton exitButton = new JButton("Exit");
              exitButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(1);
              buttonPanel.add(exitButton);
              gui.add(southPanel, BorderLayout.SOUTH);
              gui.pack();
              gui.setVisible(true);
    }I know a lot of those buttons are missing functions, but I want to get clear on how to implement a HashMap here. Any help or insight will be greatly appreciated.

    Hey thanks for that, it was some nice insight. However I'm still stumped on how HashMap needs to work in this situation. It worked fine with an object array, but this is stumping me good. To be a little more specific, I need several functions to happen with this HashMap, each correlating with a button for the GUI.
    It needs to be able to add Item objects to the HashMap (the key is the inventory number, and the value is the Item object), it needs to be able to delete an Item object (by using the inventory number), it needs to be able to find Items by inventory number, show all Items currently in the HashMap, save the info in the HashMap to a file on disk by using ObjectStreams, and a restore button just loads the data from that file to the HashMap.
    It's a lot right? :D
    I'm struggling to get anything to work with a HashMap however. If I could get some assistance with any of these functions, I would greatly appreciate it. Here's my updated code:
    import java.util.HashMap;
    import java.util.Iterator;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JScrollPane;
    public class InventoryGUI {
         //private static Item[] item = new Item[10];
         HashMap hash = new HashMap();
         private static int count = 0;
         public static void main(String[] args) {
              JFrame gui = new JFrame("Project 2 GUI");
              gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              JPanel inputPanel = new JPanel();
              inputPanel.setLayout(new GridLayout(5,2));
              inputPanel.add(new Label("Inventory Number"));
              final JTextField numberField = new JTextField(15);
              inputPanel.add(numberField);
              inputPanel.add(new Label("Name"));
              final JTextField nameField = new JTextField(15);
              inputPanel.add(nameField);
              inputPanel.add(new Label("Manufacturer"));
              final JTextField manField = new JTextField(15);
              inputPanel.add(manField);
              inputPanel.add(new Label("Description"));
              final JTextField descField = new JTextField(15);
              inputPanel.add(descField);
              inputPanel.add(new Label("Price"));
              final JTextField priceField = new JTextField(15);
              inputPanel.add(priceField);
              gui.add(inputPanel, BorderLayout.NORTH);
              final DefaultListModel dfl = new DefaultListModel();
              JList jl = new JList(dfl);
              JScrollPane jsp = new JScrollPane(jl);
              gui.add(jsp);
              JPanel southPanel = new JPanel();
              southPanel.setLayout(new GridLayout(2,1));
              final JTextField errorMsg = new JTextField();
              errorMsg.setEditable(false);
              southPanel.add(errorMsg);
              JPanel buttonPanel = new JPanel();
              southPanel.add(buttonPanel);
              JButton addButton = new JButton("Add");
              addButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        String number = numberField.getText();
                          numberField.setText("");
                         String name = nameField.getText();
                          nameField.setText("");
                         String manufacturer = manField.getText();
                          manField.setText("");
                         String description = descField.getText();
                          descField.setText("");
                         float price = Integer.parseInt(priceField.getText());
                          priceField.setText("");
                             Item myItem=new Item(number, name, manufacturer, description, price);
                               hash.put(number, myItem);
                               count++;
              buttonPanel.add(addButton);
              JButton deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                   dfl.clear();
                   String number = numberField.getText();
                    numberField.setText("");
                   hashMap.remove(number);
              buttonPanel.add(deleteButton);
              JButton findButton = new JButton("Find");
              findButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                        String number = numberField.getText();
                           numberField.setText("");
                        Item temp = new Item(hashMap.get(number));
                              dfl.addElement(temp);
              buttonPanel.add(findButton);
              JButton showButton = new JButton("Show");
              showButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                          for (Item p : item) {
                              dfl.addElement(p);
              buttonPanel.add(showButton);
              JButton saveButton = new JButton("Save");
              saveButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(saveButton);
              JButton restoreButton = new JButton("Restore");
              restoreButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(restoreButton);
              JButton exitButton = new JButton("Exit");
              exitButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(1);
              buttonPanel.add(exitButton);
              gui.add(southPanel, BorderLayout.SOUTH);
              gui.pack();
              gui.setVisible(true);
    }Thanks for any help you can give me!

  • Having Problems with Hashmap

    Hi, I'm currently creating a sparsematrix for my assignment using a hash map however i've come across a problem with how i can set an element and returning using key objects
    My setElement method is
    public void setElement(int nrow, int ncol, float value) throws
    MatrixException {
    data.put(new SparseNode(nrow,ncol), value);
    and my get element is
    public float getElement(int row, int col) throws MatrixException {
    SparseNode node = new SparseNode(row, col);
              if (!data.containsKey(node)) {
              return 0;
    return (Float) data.get(node);
    where data is the map and node would be the key. The problem comes when i set the value where i give a key and this is set into the hashmap. unfortunatly the key is lost when the method exits so using the getElement method by creating a sparsenode with same characteristics as the original key won't work simply because it's not the original key. Is there another way to get around this? or some way to store the key.

    ok well i changed to to not include the SparseNode. Now it works but very very slow. I also noticed another post with a user with the same problem but it didn't really explain how to fix it properly. Any suggestions to make this code faster?
    import java.io.*;
    import java.util.*;
    public class SparseMatrix implements Matrix{
        private HashMap data; // non zero elements
         private int rows;
         private int columns;
        public SparseMatrix(int row, int columns) {
            data = new HashMap(row*columns);
            this.rows=row;
            this.columns=columns;
        public float getElement(int row, int col) throws MatrixException {
                if (row < 0 || col < 0 || row > this.getNumRows() || col > this.getNumCols()) {
                throw new MatrixException("Row or Column Number Beyond Dimension");
                     if (!data.containsKey((row*this.getNumCols()+col))) {
                        return 0;
            return (Float) data.get((row*this.getNumCols()+col));
        public void setElement(int nrow, int ncol, float value) throws MatrixException {
    //        if (row > this.row || col > this.col) {
    //           throw new MatrixException("Matrix index out of range");
            data.put((nrow*this.getNumCols()+ncol), new Float(value));
        public boolean isZero() {
            return data.isEmpty();
        // return the total number of rows in the matrix
       public int getNumRows(){
            return rows;
       // return the total number of rows in the matrix
       public int getNumCols(){
            return this.columns;
       // transpose matrix and return result as new matrix
        public Matrix transpose() {
            SparseMatrix a = new SparseMatrix(this.getNumCols(), this.getNumRows());
            for (int i =1 ; i<=this.getNumRows();i++) {
                for (int j = 1;j<=this.getNumCols();j++){
                      float value = getElement(i,j);
                     a.setElement(j, i, value );
            return a;
        * Subtracts a matrix to the current matrix and returns result as new matrix
        * @param a The Matrix to be subtracted
        * @return Returns the new matrix
       public Matrix subtract(Matrix a) throws MatrixException{
                 if (this.getNumRows() != a.getNumRows() || this.getNumCols() != a.getNumCols())
                    throw new MatrixException("Subtraction Cannot be Done due to Matrix Dimension MisMatch");
                if (a.isZero())
                    return this;
                    SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= columns; j++) {          
                     float value = a.getElement(i,j);
                     float result = this.getElement(i,j) - value;
                     if (result < 0 || result > 0) {
                         ResultMatrix.setElement(i,j,result);
                 return ResultMatrix;
        // add matrix and return result as new matrix
        public Matrix add(Matrix a) throws MatrixException {
                if (this.getNumRows()!= a.getNumRows() || this.getNumCols()!= a.getNumCols())
                throw new MatrixException("Addition Cannot be Done due to Matrix Dimension MisMatch");
            if (this.isZero())
                return a;
            if (a.isZero())
                return this;
                SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= columns; j++) {          
                     float value = a.getElement(i,j);
                     float result = this.getElement(i,j) + value;
                     if (result < 0 || result > 0) {
                         ResultMatrix.setElement(i,j,result);
                 return ResultMatrix;
    // multiply matrix and return result as new matrix
         public Matrix multiply(Matrix a) throws MatrixException {
                              if (this.getNumCols() != a.getNumRows())
                throw new MatrixException("Multiplication Cannot be Done due to Matrix Dimension MisMatch");
            if (this.isZero() || a.isZero())
                SparseMatrix Temp = new SparseMatrix(this.getNumRows(), a.getNumCols());
                return Temp;
             SparseMatrix ResultMatrix = new SparseMatrix(this.getNumRows(), this.getNumCols());
              for(int i=1;i<=this.getNumRows();i++)
                   for(int j=1;j<=a.getNumCols();j++)
                                  float Result =0;
                                  for(int k=1;k<a.getNumCols();k++)
                                       Result = Result + this.getElement(i,k)*a.getElement(k,j);
                                  ResultMatrix.setElement(i,j,Result);
              return ResultMatrix;
         // print matrix in the format:
       // a11 a12 ... a1m
       // an1 an2 ... anm
        public void print(PrintStream out) {
             //System.out.println(data.toString() +"\n=====================");
            for (int i = 1; i <= this.getNumRows(); i++) {
                for (int j = 1; j <= this.getNumCols(); j++) {
                    float aData = this.getElement(i, j);
                    out.print(" " + aData + "");
                out.println();
    }

  • Help needed with hashmaps

    Hi friends,
    I am new to java programming and I have learnt a lot from this forum. Hope you find out what's wrong with the following program:
    the error message says
    "Cannot find symbol
    Symbol : method put()
    Location : ids520.HashMap"
    package ids520;
    import java.util.*;
    public class UserHashMap {
         private HashMap hashMap;
         public UserHashMap()
                 HashMap hashMap = new HashMap();
              hashMap.put("user1", "easy11");           //Program shows errors here saying "Cannot find symbol                  
              hashMap.put("user2", "easy21");           // Symbol : method put()
              hashMap.put("user3", "easy31");           // Location : ids520.UserHashMap
         public HashMap getHashMap() {
              return hashMap;
         public void setHashMap(HashMap hashMap) {
              this.hashMap = hashMap;
    }{code}{code}{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    This is one of the programs..
    package chatServer;
    import ids520.UserHashMap;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    //import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class MultiThreadServer extends JFrame{
        private JTextArea taServerState;
        public static void main(String[] args) {
            new MultiThreadServer();
        public MultiThreadServer() {
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(taServerState = new JTextArea(450,250));
            getContentPane().add(new JScrollPane(taServerState), BorderLayout.CENTER);
            taServerState.setEditable(false);
            setTitle("MultiThread Server");
            setSize(500, 300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            try {
                ServerSocket serverSocket = new ServerSocket(8000);
                taServerState.append("MultiThreadServer started at " + new Date() + '\n');
                int clientNo = 1;
                while(true) {
                    Socket connectToClient = serverSocket.accept();
                    taServerState.append("Starting thread client " + clientNo + " at" + new Date() + '\n');
                    InetAddress clientInetAddress = connectToClient.getInetAddress();
                    taServerState.append("Client " + clientNo + "'s hostname is " + clientInetAddress.getHostName() + "\n");
                    taServerState.append("Client " + clientNo + "'s hostaddress is " + clientInetAddress.getHostAddress() + "\n");
                    HandleAClient thread = new HandleAClient(connectToClient);
                    thread.start();
            } catch(IOException ex) {
                System.err.println("Error occured: " + ex);
        class HandleAClient extends Thread {
            private Socket connectToClient;
            public HandleAClient(Socket socket) {
                connectToClient = socket;
            public void run() {
                String loginStatus;
                try {
                    DataInputStream isFromClient = new DataInputStream(connectToClient.getInputStream());
                    DataOutputStream osToClient = new DataOutputStream(connectToClient.getOutputStream());
                    while(true) {
                        String ipPacket = isFromClient.readUTF();
                        String []pcktParts = ipPacket.split(":");
                        String message = pcktParts[0];
                        String msgType = pcktParts[1];
                        String to = pcktParts[2];
                        String from = pcktParts[3];
                        if(msgType.equals("login")) {
                            String []loginInfo = message.split(";");
                            String username = loginInfo[0];
                            String password = loginInfo[1];
                            UserHashMap usermap = new UserHashMap();
                            HashMap userMap1;
                             userMap1 = usermap.getHashMap();
                            taServerState.append("User with username" + username + "trying to login");
                            if(((String)userMap1.get(username)).equals(password)) {
                                loginStatus = "pass";
                                taServerState.append("Login is authenticated");
                            } else {
                                loginStatus = "fail";
                                taServerState.append("User not authenticated, username or password could be wrong");
                            osToClient.writeChars(loginStatus);
                } catch(IOException e) {
                    System.err.println("Error Encountered: "+ e);
    }

Maybe you are looking for

  • Massive Deletion of Open Sales Orders/Deliveries

    Hi, I was wondering if anyone knows a massive transaction to delete open sales orders and deliveries. I try using de MASS transaccion but here I can only reject the items (in sales orders) but the thing is that the customer wants the open orders and

  • App.exportMiniFolio error

    Hi I removed all prerelease versions. Then dowloaded and installed the new versions for ID 5.0 Now in the overlay creator if I try to hit the Preview at the bottom. I get a app.exportMiniFolio error. Same thing if I try to use the Folio builder and i

  • Error in cube data

    Hi experts!!! I load data to a cube which contains monthly value and YTD keyfigures.Monthly value is calculated in start routines while data is being loaded from DSO to cube. Monthly value of cube = YTD value of cube for present month-YTD value of pa

  • BI Lauch Pad link not working

    Hi I Installed BI 4.1 Trial Version. I am able to open the BI Launch Pad Link on the Windows Server BUT not in client laptop 1. I checked the Tomcat is working fine checking the tomcat link http://systemname:port no 2. same link able to access in win

  • I can't open some documents On my Pages app' - any ideas anyone please?

    Documents created before a certain date have been replaced by a picture of an ink well and a fountain pen and when I try to open them the iPad keeps going back to the menu page. I've tried resetting and deleting the app' and reinstalling and none of