aspose file tools*
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 Java 8 in Action this week in the Java 8 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: 13884
    
  10

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
Greenhorn

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: http://aspose.com/file-tools
 
subject: Array of HashMaps
 
Similar Threads
need linux command.
Invalid operation for forward only resultset : last
Value update in hashmap
Printing HashMap!
getting array values from HashMap!!!