Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of HashMaps

 
Sharma Vinit
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15490
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Sharma Vinit
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper.. I understood where i was going wrong.

Your solution saved my day
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic