Java 从Mongodb检索bson文档并添加到Arraylist时出现Nullpointerexception
下面是从DB检索最后10篇文章并返回列表的代码 我在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
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
,使其成为一个空列表。查看我的最新答案