1

我已经编写了以下代码行,似乎一切正常,但是当我看到结果不正确时。

在这里,我定义了一个 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

如您所见,结果不同,但我希望结果应该相同。我的问题在哪里?谢谢

4

2 回答 2

3

您需要在每个循环上创建新实例,否则将更新相同的实例。列表维护对对象的引用,它们不包含对象的副本。

for(int i=0; i<resepi.getResepiId().size(); i++) {
    KategoriRecipeList kategori = new KategoriRecipeList();
    kategori.setKategoriName(kategoriName);
    kategori.setResepiId(resepi.getResepiId().get(i));
    ....
}
于 2012-09-08T19:22:29.513 回答
3

这条线

分类食谱列表 分类 = 新分类食谱列表();

需要在 for 循环内你必须每次都创建一个新对象

于 2012-09-08T19:22:58.890 回答