Как добавить коллекции классов в класс, который имеет коллекцию - PullRequest
0 голосов
/ 23 мая 2011

У меня есть ArrayList of Products, который я хочу добавить к моей карте класса продаж в моем классе Product.Цель этого состоит в том, чтобы иметь запись каждого продукта, что было куплено с ним и сколько.

ArrayList<Product> array = new ArrayList<Product>(tempProducts.values());
for (int i = 0; i < array.size() - 1; i++) {
            for (int j = i+1; j < array.size() ; j++) {
                update(array.get(i), array.get(j));
            }
        }
    }


 public static void update(Product a, Product b)
{



    if (a.getId().compareToIgnoreCase(b.getId()) != 0) {
        if (a.getCollection().get(b.getId()) != null) {
            a.getCollection().get(b.getId()).incsales();

        } else {

            a.getCollection().put(b.getId(), new sale(b.getId(), b.getDesc()));
        }
        if (b.getCollection().containsKey(a.getId())) {
            a.getCollection().get(b.getId()).incsales();

        } else {
            b.getCollection().put(a.getId(), new sale(a.getId(), a.getDesc()));
        }
    }



}

Результаты, которые я получаю:

 Description : Balsamic Ital Dressing 2.5L Kraft
 Sales : 80
 This product was purchased the most with :
 1 0000795501891 Babyfood, dinner, vegetables and lamb, junior (7)
 2 0000053838530 Cheese, cottage, creamed, large or small curd (7)
 3 0001580359521 Macadamia Nuts Kernels 1KG Natural Grocer (7)
 4 0001549470330 Orange Juice Long Life 2L Just Juice (7)
 5 0000102800862 Babyfood, fruit, pears and pineapple, junior (5)
 Description : Mighty Soft Bread Multigrain Sandwich 700g
 Sales : 78
 This product was purchased the most with :
 1 0000250315049 Babyfood, cereal, barley, prepared with whole milk (7)
 2 0001906925229 Coles Bread Multigrain Sliced 700g (7)
 3 0001348704022 Honey Portion 48X14G Beerenberg (7)
 4 0000965461817 Milk, canned, evaporated, nonfat, with added vitamin A and vitamin D (7)
  5 0000883156398 Abotts Village Bakery Wholemeal Farmhouse 750g (5)

я должен получить:

   Description : Balsamic Ital Dressing 2.5L Kraft 
  Sales : 80
  This product was purchased the most with :
  1 0000102800862 Babyfood, fruit, pears and pineapple, junior (4)
  2 0000449778467 Decaf Ground Coffee 250G Cremadoro (4)
  3 0001549470330 Orange Juice Long Life 2L Just Juice (4)
  4 0000795501891 Babyfood, dinner, vegetables and lamb, junior (3)
  5 0000708398761 Butter, salted (3)
  Description : Mighty Soft Bread Multigrain Sandwich 700g
  Sales : 78
  This product was purchased the most with :
  1 0000497527798 Cream Cheese Philadelphia Light 1KG Kraft (4)
  2 0000890198554 Mayonnaise Fat Free 2.7KG Kraft (4)
  3 0000298379350 Milk, buttermilk, dried (4)
  4 0000250315049 Babyfood, cereal, barley, prepared with whole milk (3)
  5 0000966839744 Babyfood, cereal, with egg yolks, strained (3)

Любые подсказки или подсказки о том, как я могу остановить его от чрезмерного подсчета?


обновление : Tried Péter Török Предложение, Получил этот результат:

 Description : Balsamic Ital Dressing 2.5L Kraft
    Sales : 80
    This product was purchased the most with :
    1 0001549470330 Orange Juice Long Life 2L Just Juice (7)
    2 0000102800862 Babyfood, fruit, pears and pineapple, junior (5)
    3 0000708398761 Butter, salted (5)
    4 0002140785264 Egg, whole, dried, stabilized, glucose reduced (5)
    5 0000422477496 Essence Parisian 575ML Aeroplane (5)
    Description : Mighty Soft Bread Multigrain Sandwich 700g
   Sales : 78
   This product was purchased the most with :
    1 0001906925229 Coles Bread Multigrain Sliced 700g (5)
    2 0000127034559 Limonata 24X200ML San Pellegrino (5)
    3 0001736609947 Babyfood, dessert, custard pudding, vanilla, junior (3)
    4 0002028785759 Babyfood, dinner, beef stew, toddler (3)
    5 0000432411254 Babyfood, juice, orange and pineapple (3)

1 Ответ

1 голос
/ 23 мая 2011

Я думаю, что корень проблемы в том, что для каждой пары продуктов с индексом (i, j) вы обрабатываете их дважды в цикле: один раз как (i, j), затем как (j, i).Вместо этого попробуйте использовать этот цикл:

for (int i = 0; i < array.size() - 1; i++) {
        for (int j = i + 1; j < array.size(); j++) {
            update(array.get(i), array.get(j));
        }
    }
}

(здесь счетчик внутреннего цикла начинается с i + 1 вместо 0. Обратите внимание также, что я изменил оба условия цикла, потому что я думаю, что ваши исходные циклы выключены наодна ошибка - последний элемент в массиве имеет индекс array.size() - 1.)

Update

И здесь также есть ошибка копирования-вставки:

    if (b.getCollection().containsKey(a.getId())) {
        a.getCollection().get(b.getId()).incsales();

тогда как это должно быть

        b.getCollection().get(a.getId()).incsales();
...