I am trying to extract a linkedlist from an array of linkedlist and am stuck. After extracting this linkedlist, I would need to sum the number of fruits in each basket in each linkedlist. For example, Basket 0 returns 174, Basket 1 returns 147, etc.
I’ve tried using an iterator and listIterator (as well) to extract the number of fruits but I am not getting anywhere. Anyone who can help? Some pointers/hints so I can start coding again.
public class ArrayLinkedList {
final static int NUM_OF_ROWS = 32767;
public static void main(String [] args) {
List[] basket = new List [NUM_OF_ROWS];
for (int i = 0; i < NUM_OF_ROWS; i++) {
basket[i] = new LinkedList();
}
basket[0].add("1,APPLE,12");
basket[1].add("2,APPLE,14");
basket[1].add("3,APPLE,9");
basket[2].add("4,APPLE,90");
basket[2].add("5,APPLE,13");
basket[0].add("1,ORANGE,45");
basket[0].add("2,ORANGE,19");
basket[1].add("3,ORANGE,67");
basket[1].add("4,ORANGE,33");
basket[0].add("1,BANANA,2");
basket[0].add("2,BANANA,96");
basket[1].add("3,BANANA,16");
basket[1].add("4,BANANA,8");
basket[2].add("5,BANANA,14");
basket[2].add("6,BANANA,26");
basket[3].add("7,BANANA,8");
basket[3].add("8,BANANA,5");
for (int i = 0; i < 5; i++) {
System.out.println("Basket " + i + ": " + rows[i].toString());
}
}
}
You should not use a string to store multiple information. This would force you to parse the string each time you want to get a part of the information. I don’t know what
"1,APPLE,12"represents, but you should use an object instead of this string :And then, your array of baskets can be built like this :
Then, you may iterate over one of the baskets and compute the total number of fruits easily :