Solved

Assigning HashMap to HashMap.

Posted on 2004-08-31
16
1,657 Views
Last Modified: 2008-03-10
Hello Everybody,

I have a program which will parse the  input file into Key values pair and return the HashMap.
This programme is working fine. I can print out the key/value pairs. Problem is when in main method I assign this HashMap to new HashMap the values are gone.

public Static void main( String args[]) {

HashMap hm = new HashMap;

hm = parse("filename");

System.out.println(hm.get("UserID");
}

public HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}

UserID is one of the Key...I can print out from the parse program correctly.
But from main I receive value "null"
What could be the problem?

Thanks,
Kedlu
0
Comment
Question by:kedlunanu
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +3
16 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11948117
public Static void main( String args[]) {

HashMap hm = parse(new File("filename"));

System.out.println(hm.get("UserID");
}

public static HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11948610
can you post the code.
some where in the code hashmap might be getting reset.
0
 
LVL 16

Expert Comment

by:gnoon
ID: 11949120
>I can print out from the parse program correctly
Which part of the function you printed it out?

To dubug this problem, I think you should try to print it out at the end of 'parse' function before the return statement.
For example,

public static HashMap parse(File file) {
  HashMap h = new HashMap();

  // parsing and putting key/values into hash

  System.out.println(h.get("UserID");
  return h;
}

If the result still be null, so the problem should be in the parsing and putting section of the 'parse' function.
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 1

Expert Comment

by:talvio
ID: 11949547
Hi,

hmm, your code has quite a few typos in it, but after correcting those it does work:
public static void main( String args[]) {
    HashMap hm = new HashMap();
    hm = parse("filename");
    System.out.println(hm.get("UserID"));
}
public static HashMap parse(String str) {
    HashMap h = new HashMap();
//     parsing and putting key/values into hash
    h.put("UserID", "Yo!");  // <-- added to test the function
    return h;
}

But as noted by objects you should get rid the first HashMap creation as it is totally unnecessary.

I'd encourage you to look at java.util.Properties -class. That would seem to fit to your problem.
Properties is a hashmap like (actually extends HashTable), but it stores only Strings. This is quite
usefull as you are using Strings in your hashmap. This would free you from unnecessary casting
you need to do al the time with HashMap. Also Properties offers some very usefull methods such as:
- void load(InputStream inStream) parses your file for you, if the format is suitable for you
- String getProperty(String key, String defaultValue) lets you set a default value if no value is found.

Look at the javadoc of java.util.Properties, it should ease your work.

br,
-jT
0
 

Author Comment

by:kedlunanu
ID: 11955622
public HashMap parse(File file) {
            
            String line;
            StringTokenizer st ;
            HashMap hm = new HashMap();
            String s;
            String s1;      
                  
            try{
                  
            BufferedReader in = new BufferedReader(new FileReader(file));
                  while ((line=in.readLine()) != null){
                        st = new StringTokenizer(line,"=");
                        s = st.nextToken();
                        s1= st.nextToken();
                                              hm.put(s,s1);
                              
                        }
                        
                  }catch(IOException e) {
                        
                        System.out.println("IOException" + e);
                  }
            
              System.out.println(hm.get("UserID"));
                                  return hm;
            
      }

public static void main (String args[]) {

HashMap hmt = parseConfigFile("config.txt");
System.out.println(hmt.get("UserID"));
      }

I can't print out "UserID" from main method or parse method. I was printing tokens and they were getting printed correct.

Please see what is the problem in the program.
Thanks
0
 
LVL 35

Expert Comment

by:girionis
ID: 11955799
> I can't print out "UserID" from main method or parse method.

Are you sure the "UserID" (check for case sensitivity) exists as a key?
0
 

Author Comment

by:kedlunanu
ID: 11955937
Yes...I'm printing out other fields too...but they are returning 'null' value.
I guess this is the problme of scope? becasue after I insert values inside the hash, if immediately after that I print out...they are printing out correct.

 Comment from objects  feedback
Date: 08/31/2004 05:41PM PDT
 Comment  


public Static void main( String args[]) {

HashMap hm = parse(new File("filename"));

System.out.println(hm.get("UserID");
}

public static HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}

 
Comment from expertmb  feedback
Date: 08/31/2004 08:17PM PDT
 Comment  


can you post the code.
some where in the code hashmap might be getting reset.
 
Comment from gnoon  feedback
Date: 08/31/2004 09:59PM PDT
 Comment  


>I can print out from the parse program correctly
Which part of the function you printed it out?

To dubug this problem, I think you should try to print it out at the end of 'parse' function before the return statement.
For example,

public static HashMap parse(File file) {
  HashMap h = new HashMap();

  // parsing and putting key/values into hash

  System.out.println(h.get("UserID");
  return h;
}

If the result still be null, so the problem should be in the parsing and putting section of the 'parse' function.
 
Comment from talvio  feedback
Date: 08/31/2004 11:31PM PDT
 Comment  


Hi,

hmm, your code has quite a few typos in it, but after correcting those it does work:
public static void main( String args[]) {
    HashMap hm = new HashMap();
    hm = parse("filename");
    System.out.println(hm.get("UserID"));
}
public static HashMap parse(String str) {
    HashMap h = new HashMap();
//     parsing and putting key/values into hash
    h.put("UserID", "Yo!");  // <-- added to test the function
    return h;
}

But as noted by objects you should get rid the first HashMap creation as it is totally unnecessary.

I'd encourage you to look at java.util.Properties -class. That would seem to fit to your problem.
Properties is a hashmap like (actually extends HashTable), but it stores only Strings. This is quite
usefull as you are using Strings in your hashmap. This would free you from unnecessary casting
you need to do al the time with HashMap. Also Properties offers some very usefull methods such as:
- void load(InputStream inStream) parses your file for you, if the format is suitable for you
- String getProperty(String key, String defaultValue) lets you set a default value if no value is found.

Look at the javadoc of java.util.Properties, it should ease your work.

br,
-jT

 
Comment from kedlunanu
Date: 09/01/2004 10:33AM PDT
 Your Comment  


public HashMap parse(File file) {
         
          String line;
          StringTokenizer st ;
          HashMap hm = new HashMap();
          String s;
          String s1;    
               
          try{
               
          BufferedReader in = new BufferedReader(new FileReader(file));
               while ((line=in.readLine()) != null){
                    st = new StringTokenizer(line,"=");
                    s = st.nextToken();
                    s1= st.nextToken();
                    hm.put(s,s1);

                   /*********    printing out immediately ***************/

                    System.out.ptintln(hm.get(s).toString());
                         
                   /*******************************************/
                    }
                   
               }catch(IOException e) {
                   
                    System.out.println("IOException" + e);
               }
         
            System.out.println(hm.get("UserID"));
                                  return hm;
         
     }
 
 
0
 
LVL 35

Expert Comment

by:girionis
ID: 11956022
It's not matter of scope since you are returning the HashMap. So do you see the UserID inside the creation method but not outside (in the main)?
0
 

Author Comment

by:kedlunanu
ID: 11956083
I see UserID immediately after I put the entries in the HashMap but not just before I'm returning the HashMap...is weird
0
 
LVL 35

Expert Comment

by:girionis
ID: 11956579
What is the value os the "s" here:

System.out.ptintln(hm.get(s).toString());

What happens if you do

System.out.println("s: " + s);
0
 

Author Comment

by:kedlunanu
ID: 11956626
This is the output for your porgram:

s: IsLocal      
s: MachineName
s: UserID
s: Password
s: Database
s: DatabaseAlias
s: SchemaName


So the fields are printing out correctly.
I dont know what could be the problem.
0
 
LVL 35

Accepted Solution

by:
girionis earned 50 total points
ID: 11957775
There might be some space in front after the key. What happens if you do this:

 hm.put(s.trim(),s1);

Do you still have the same problem?
0
 
LVL 92

Expert Comment

by:objects
ID: 11958463
What is the output from the code you are using?
0
 

Author Comment

by:kedlunanu
ID: 11958505
This file is a profile...I need to parse this file and use values of the parameter in the program.
Username,password,database based on this value program will run. Automating our product.
0
 

Author Comment

by:kedlunanu
ID: 11958564
Hey girionis...
It worked with trim().
It was indeed considering some space after each word and so was not able to recognize the key.
Thanks so much for your valueable suggestions.
Kedlu
0
 
LVL 35

Expert Comment

by:girionis
ID: 11960800
:)
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question