• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array of HashMaps

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.



 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jesper.. I understood where i was going wrong.

Your solution saved my day
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic