3

I have a List of ArrayList and would like to add predefined values to it using addall

List<ArrayList<String>> places;

But I'm not sure how to do so. Will it look something like the following:

places.addall(["a","b","c"],["aa","bb","cc"]....);

I tried that and it's not working.

2
  • Possible duplicate of 2 dimensional array list Commented Feb 17, 2016 at 15:19
  • You want a two dimensional list. See the link for various code samples. Commented Feb 17, 2016 at 15:20

2 Answers 2

3

I don't think you can use addAll in that way, since addAll expects a Collection as the parameter; in your case it should be a Collection<? extends List<String>>

So, you need to create a Collection with the array looking data that you have and then add it to your places Collection.

The closest that i can think of is to do something as below,

    List<List<String>> places = new ArrayList<List<String>>();
    String[] string1 = new String[]{"a", "b", "c"};
    String[] string2 = new String[]{"aa", "bb", "cc"};
    places.add(Arrays.asList(string1));
    places.add(Arrays.asList(string2));

If you really want to use addAll then you'll have to do something like this,

    List<List<String>> tempPlaces = new ArrayList<List<String>>();
    String[] string1 = new String[]{"a", "b", "c"};
    String[] string2 = new String[]{"aa", "bb", "cc"};
    tempPlaces.add(Arrays.asList(string1));
    tempPlaces.add(Arrays.asList(string2));

    List<List<String>> places = new ArrayList<List<String>>();
    places.addAll(tempPlaces);
Sign up to request clarification or add additional context in comments.

2 Comments

I think you should state that OP's confusion is that addAll expects a Collection, and that Arrays.asList() returns a Collection.
Correct, the contract is addAll(Collection<? extends E>) docs.oracle.com/javase/7/docs/api/java/util/…
1

For your case first you add values to the ArrayList ArrayList al = new ArrayList(); al.add("Hi"); al.add("hello"); al.add("String"); al.add("Test"); ArrayList al1 = new ArrayList(); al1.add("aa"); al1.add("bb"); al1.add("cc"); al1.add("dd"); Now you add these elements to your List

List> places;

places.add(al); places.add(al1);

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.