Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 726
pankaj Avatar asked May 04 '26 10:05

pankaj


1 Answers

....
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]]

like image 79
Niko Avatar answered May 07 '26 00:05

Niko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!