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.

halfer
  • 19,824
  • 17
  • 99
  • 186
hello_its_me
  • 743
  • 2
  • 19
  • 52
  • Possible duplicate of [2 dimensional array list](http://stackoverflow.com/questions/10866205/2-dimensional-array-list) – rghome Feb 17 '16 at 15:19
  • You want a two dimensional list. See the link for various code samples. – rghome Feb 17 '16 at 15:20

2 Answers2

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);
Sachin
  • 901
  • 2
  • 10
  • 23
  • I think you should state that OP's confusion is that addAll expects a `Collection`, and that `Arrays.asList()` returns a `Collection`. – Clark Kent Feb 17 '16 at 15:22
  • Correct, the contract is addAll(Collection extends E>) https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll(java.util.Collection) – hagmic Feb 17 '16 at 15:24
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);