This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Array of HashMaps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array of HashMaps" Watch "Array of HashMaps" New topic
Author

Array of HashMaps

Sharma Vinit
Greenhorn

Joined: Apr 29, 2010
Posts: 5
Hi Guys

I m trying to create an array of HashMaps in the following way on NetBeans 6.8

HashMap[] map=null;
int i = 0;

while (rs.next()){

map[i] = new HashMap();

map[i].put("empid",rs.getString("EMPID"));
map[i].put("ename",rs.getString("ENAME"));
map[i].put("email",rs.getString("EMAIL"));
map[i].put("dob",rs.getString("DOB"));

i++;
}

But i am getting a nullPointerException at the line in red (map[i] = new HashMap();)
The database is correctly populated and i am able to display the values on console using System.out.println().

Can anybody help find out the problem with this code.
I am looking forward for your help and cooperation.



Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14278
    
  21

Welcome to JavaRanch. Please UseCodeTags when you post source code.

Sharma Vinit wrote:HashMap[] map=null;

// ...

But i am getting a nullPointerException at the line in red (map[i] = new HashMap();)

Ofcourse, because map is null. You need to initialise it first:

Note that arrays have a fixed size once they are created. In your code, you probably don't know beforehand how many entries the array should get (since you're reading rows from a ResultSet). Use a collection class instead of an array, for example an ArrayList - because that can be resized dynamically. Convert it to an array afterwards if needed:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Sharma Vinit
Greenhorn

Joined: Apr 29, 2010
Posts: 5
Thanks Jesper.. I understood where i was going wrong.

Your solution saved my day
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Array of HashMaps