Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从Mongodb检索bson文档并添加到Arraylist时出现Nullpointerexception_Java_Mongodb - Fatal编程技术网

Java 从Mongodb检索bson文档并添加到Arraylist时出现Nullpointerexception

Java 从Mongodb检索bson文档并添加到Arraylist时出现Nullpointerexception,java,mongodb,Java,Mongodb,下面是从DB检索最后10篇文章并返回列表的代码 我在posts.add(doc)行遇到空指针异常 我做错什么了吗 public List<Document> findByDateDescending(int limit) { List<Document> posts = null; Bson sort = Sorts.descending("date"); MongoCursor<Document> cursor = postsCo

下面是从DB检索最后10篇文章并返回列表的代码

我在
posts.add(doc)
行遇到空指针异常

我做错什么了吗

public List<Document> findByDateDescending(int limit) {

    List<Document> posts = null;
    Bson sort = Sorts.descending("date");
    MongoCursor<Document> cursor =  postsCollection.find().sort(sort).limit(limit).iterator();
    try{
        while(cursor.hasNext()){
            System.out.println("Whats wrong with code");
            Document  doc = cursor.next();
            System.out.println(doc);
            posts.add(doc); ----Null pointer exception
        }
    }
    finally {
       cursor.close();
    }
    return posts;
}
公共列表findByDateDescending(整数限制){
列表帖子=null;
Bson sort=排序。降序(“日期”);
MongoCursor=postsCollection.find().sort(sort).limit(limit).iterator();
试一试{
while(cursor.hasNext()){
System.out.println(“代码有什么问题”);
Document doc=cursor.next();
系统输出打印项次(doc);
posts.add(doc);----空指针异常
}
}
最后{
cursor.close();
}
返回岗位;
}

您定义了
posts
,但从未为其分配任何内容,因此它仍然为空。 这样的办法应该行得通

List<Document> posts = new List<>();
List posts=newlist();

感谢您的回复。我正在将每次迭代中的bson文档“doc”添加到posts列表中。如果要进行任何代码更改,请帮助我。
posts
为空。您不能向null添加/追加任何内容。我认为您希望启动
posts
,使其成为一个空列表。查看我的最新答案