Solved

Assigning HashMap to HashMap.

Posted on 2004-08-31
16
1,648 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
  • 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
 
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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 how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

708 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now