Java中List元素全部被最后一个覆盖的问题

lucksamtom 2016-07-12 07:50:23

public static void filterSome(MongoDatabase db, String col) {
MongoCollection<Document> collection = db.getCollection(col);
MongoCursor<Document> cursor = collection.find(
new Document("pci", "57").append("ta", "32"))
.sort(new Document("rsrp", 1)).iterator();

List<Loc> GpsGroup = new ArrayList<Loc>();
while (cursor.hasNext()){
Document temp = cursor.next();
Loc i = new Loc();
i = add2Loc(temp);
GpsGroup.add(i);//向List添加元素
System.out.println(i.getLog());//每次循环生成的i都是不一样的
}
cursor.close();
System.out.println(GpsGroup.get(1).getLog());
System.out.println(GpsGroup.get(10).getLog());
}


最后两句测试发现第一个元素和第十个元素的数据是一样的,遍历后发现全部元素和最后add进去的元素一样。
请问为什么呀?
...全文
432 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
gamedev˚ 2016-07-13
  • 打赏
  • 举报
回复
lucksamtom 2016-07-12
  • 打赏
  • 举报
回复
最后发现是Loc类的问题,Loc类中的类变量都写成了static的,把static删掉就好了。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧