-4

compiler giving NullPointerException error, dont know why. please help?

public List<DBObject> findByDateDescending(int limit) {

    List<DBObject> posts = null;
    // XXX HW 3.2,  Work Here
    // Return a list of DBObjects, each one a post from the posts collection
    DBCursor cur=postsCollection.find().sort(new BasicDBObject("date",-1)).limit(limit);
   while(cur.hasNext()){
/*==>> error */   posts.add(cur.next());
    }//end while 

    return posts;
}
kenju
  • 5,866
  • 1
  • 41
  • 41
exgenome
  • 69
  • 1
  • 1
  • 2
  • You did assign only `null` to `posts`, and then you try to access it, of course you get NPE. – amit Apr 05 '14 at 20:13
  • 2
    [What is a NullPointerException?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception). And the official docs: [NullPointerException](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html) – keyser Apr 05 '14 at 20:14
  • Also, the **compiler** does not give you NPE, the jvm does. – amit Apr 05 '14 at 20:14
  • 2
    Next time, look at your stack trace. Then read [`NullPointerException`](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html), then put 2 and 2 together and watch the magic happen. There's only two opportunities on that line for an NPE; either `posts` or `cur` is `null`. We can easily rule out `cur` since the line before it did not have an issue. So `posts` is `null`. Make it not be `null`. – Jason C Apr 05 '14 at 20:15

1 Answers1

3

Change this:

List<DBObject> posts = null;

To this:

List<DBObject> posts = new ArrayList<DBObject>();
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • hey man, thanks it worked!! what was the error? – exgenome Apr 05 '14 at 20:17
  • @exgenome: You're welcome. The error, as explained in the comments to your question, is that you are not initializing the `post` variable. To be more accurate, you are initializing it to `null`, hence the Null-Pointer exception that you get during runtime. I thought it was pretty obvious from the answer, so I didn't bother to explain it... Don't forget to click the V in order to accept the answer :) – barak manos Apr 05 '14 at 20:20