3

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"]
3
  • 2
    Do you have multiple ´times´ arrays or single and you need to split it evenly? Commented Dec 24, 2017 at 7:06
  • 2
    do you add "a" to "ccc" in that single for loop? Commented Dec 24, 2017 at 7:07
  • 2
    What is your times array? Commented Dec 24, 2017 at 7:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.