This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array of HashMaps" Watch "Array of HashMaps" New topic

Array of HashMaps

Sharma Vinit

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 ({

map[i] = new HashMap();



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: 14074

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 7 API documentation
Scala Notes - My blog about Scala
Sharma Vinit

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

Your solution saved my day
I agree. Here's the link:
subject: Array of HashMaps
Similar Threads
need linux command.
Invalid operation for forward only resultset : last
Value update in hashmap
getting array values from HashMap!!!
Printing HashMap!