pankaj
pankaj

Reputation: 8348

Creating arraylist of array

I am trying to create an Arraylist which has array of Strings at each index. I have used following code:

ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();
String[] str = new String[times.size()];//times is an Arraylist of string
for(int i=0; i<times.size();i++){
    str[i] = times.get(i);
}
deliveryTimes.add(str);

With above code all the elements of str array are added at different index in deliveryTimes arraylist. But I want to add str as array at a index. So it should be like following:

[["a","b","c"],["aa","bb","cc"],["aaa","bbb","ccc"]]

But it is like:

["a","b","c","aa","bb","cc","aaa","bbb","ccc"]

Upvotes: 3

Views: 132

Answers (2)

rimonmostafiz
rimonmostafiz

Reputation: 1471

Your deliveryTimes list only contains one String[]. Add multiple String[] to deliveryTimes list.

ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();

String[] one = new String[]{"a", "b", "c"};
String[] two = new String[]{"aa", "bb", "cc"};
String[] three = new String[]{"aaa", "bbb", "ccc"};

deliveryTimes.add(one);
deliveryTimes.add(two);
deliveryTimes.add(three);

for (String[] str : deliveryTimes) {
    System.out.println(Arrays.toString(str));
}

Output

[a, b, c]

[aa, bb, cc]

[aaa, bbb, ccc]

You need to split your times list and add them to deliveryTimes List separately.

Upvotes: 0

Niko
Niko

Reputation: 8153

....
String[] first = new String[]{"a", "b", "c"};
String[] second = new String[]{"aa", "bb", "cc"};
String[] third = new String[]{"aaa", "bbb", "ccc"};

addArrays(first, second, third);

...

ArrayList<ArrayList<String>> addArrays(String[]... strings) {
    ArrayList<ArrayList<String>> allTimes = new ArrayList<>(strings.length);

    for (String[] array : strings) {
        allTimes.add(new ArrayList<>(Arrays.asList(array)));
    }

    return allTimes;
}

allTimes contains: [[a, b, c], [aa, bb, cc], [aaa, bbb, ccc]]

Upvotes: 2

Related Questions