我已经编写了以下代码行,似乎一切正常,但是当我看到结果不正确时。
在这里,我定义了一个LinkedList并在其中添加了一个对象。
private LinkedList<KategoriRecipeList> createListObjects() {
LinkedList<KategoriRecipeList> list = new LinkedList<KategoriRecipeList>();
KategoriRecipeList kategori = new KategoriRecipeList();
for(int i=0; i<resepi.getResepiId().size(); i++) {
kategori.setKategoriName(kategoriName);
kategori.setResepiId(resepi.getResepiId().get(i));
kategori.setResepiName(resepi.getResepiName().get(i).trim().replaceAll("'", ""));
kategori.setImgLogoUri(resepi.getResepiImageURL().get(i));
kategori.setImgMoreUri(bitmapUrls.get(i));
Log.i("WWWWWWW", "Recipe '" + resepi.getResepiName().get(i) + "' added to list");
list.add(kategori);
}
return list;
}
当我看到日志文件时,结果如下:
09-09 03:05:29.272: I/WWWWWWW(1250): Recipe '"Chicken Cordon Bleu"' added to list
09-09 03:05:29.272: I/WWWWWWW(1250): Recipe '"Sat-Bag"' added to list
09-09 03:05:29.272: I/WWWWWWW(1250): Recipe 'Ayam Adobo ' added to list
09-09 03:05:29.272: I/WWWWWWW(1250): Recipe 'Ayam Ber’Crumble’ & ‘Fennel’ direneh Air Roselle' added to list
09-09 03:05:29.272: I/WWWWWWW(1250): Recipe 'Ayam Dua Cara' added to list
我有另一种调用上述方法的方法:
private void storeListIntoDatabase() {
Log.i(TAG, "Try to insert data into database.");
LinkedList<KategoriRecipeList> listOfObjects = createListObjects();
if(listOfObjects == null || listOfObjects.size() <= 0)
return;
for(int i=0; i<listOfObjects.size(); i++)
Log.i("KKKKKKKK", "Recipe '" + listOfObjects.get(i).getResepiName() + "' added to list");
}
日志文件中的结果如下:
09-09 03:05:29.297: I/KKKKKKKK(1250): Recipe 'Tongkeng Ayam Goreng dan Nasi Kari Leher Ayam' added to list
09-09 03:05:29.297: I/KKKKKKKK(1250): Recipe 'Tongkeng Ayam Goreng dan Nasi Kari Leher Ayam' added to list
09-09 03:05:29.297: I/KKKKKKKK(1250): Recipe 'Tongkeng Ayam Goreng dan Nasi Kari Leher Ayam' added to list
09-09 03:05:29.297: I/KKKKKKKK(1250): Recipe 'Tongkeng Ayam Goreng dan Nasi Kari Leher Ayam' added to list
09-09 03:05:29.297: I/KKKKKKKK(1250): Recipe 'Tongkeng Ayam Goreng dan Nasi Kari Leher Ayam' added to list
正如您所看到的结果不同但我希望结果应该相同。我的问题在哪里?感谢
答案 0 :(得分:3)
您需要在每个循环上创建新实例,否则将更新相同的实例。列表维护对象的引用,它们不包含对象的副本。
for(int i=0; i<resepi.getResepiId().size(); i++) {
KategoriRecipeList kategori = new KategoriRecipeList();
kategori.setKategoriName(kategoriName);
kategori.setResepiId(resepi.getResepiId().get(i));
....
}
答案 1 :(得分:3)
这一行
KategoriRecipeList kategori = new KategoriRecipeList();
需要在for循环中 你必须每次都创建一个新对象