So, I have this code , where basically I want to put a String Array to inside of an ListArray, then put that ListArray to inside of another ListArray. While I know how to put a new object of Array , I can't seem to find a way to put a new ListArray object to another ListArray
import java.util.ArrayList;
import java.util.List;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<List<String[]>> menues = new ArrayList<>();
ArrayList<String[]> items = new ArrayList<String[]>();
String price = "12ドル";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
String name = "Item Code-" + String.valueOf(i) + String.valueOf(j);
items.add( new String[]{name, price} );
}
menues.add(items); // This line is the cause
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(menues.get(i).get(j)[0]);
}
}
}
}
There Result I expect is
Item Code-00
Item Code-01
Item Code-02
Item Code-03
Item Code-04
Item Code-10
Item Code-11
Item Code-12
Item Code-13
Item Code-14
Item Code-20
Item Code-21
Item Code-22
Item Code-23
Item Code-24
The Result THAT I GOT (basically just repeating the same thing)
Item Code-00
Item Code-01
Item Code-02
Item Code-03
Item Code-04
Item Code-00
Item Code-01
Item Code-02
Item Code-03
Item Code-04
Item Code-00
Item Code-01
Item Code-02
Item Code-03
Item Code-04
asked Mar 28, 2018 at 13:41
1 Answer 1
You need to move the creation of items
inside the loop:
for (int i = 0; i < 3; i++) {
ArrayList<String[]> items = new ArrayList<String[]>();
for (int j = 0; j < 5; j++) {
String name = "Item Code-" + String.valueOf(i) + String.valueOf(j);
items.add( new String[]{name, price} );
}
menues.add(items); // This line is the cause
}
Otherwise you add the same items
all over again which results in the outer list containing the same list 3 times.
answered Mar 28, 2018 at 13:45
Comments
lang-java