2

I'm trying to create an array list of arrays. When I'm done, I want the array list to look like this:

[ [Mary] , [Martha,Maggie,Molly] ]

I'm trying to accomplish this by first defining "Mary" as a string array of length 1, and defining "Martha, Maggie, Molly" as a string array of length three. Then I attempt to add these arrays to an array list. But alas, the array list will not accept the arrays. Take a look:

String[] s1 = new String[1];
String[] s3 = new String[3];

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

s1[0]="Mary";
s3[0]="Martha";
s3[1]="Maggie";
s3[2]="Molly";

list1.add(s1[0]);
list1.add(s3[0]);
list1.add(s3[1]);
list1.add(s3[2]);

Any ideas on how I can add these arrays to list1, in order to form an array list of arrays?

squiguy
  • 32,370
  • 6
  • 56
  • 63
kjm
  • 113
  • 2
  • 2
  • 10

4 Answers4

5

You're adding the individual strings to the ArrayList instead of the String arrays that you created.

Try just doing:

list1.add(s1);
list1.add(s3);
squiguy
  • 32,370
  • 6
  • 56
  • 63
  • Thanks. One quick follow-up: when I enter: System.out.println("list1") I don't see the array list I expected. Instead, I see some kind of gibberish. Any idea what's going on with that? – kjm Aug 16 '13 at 03:13
  • @kjm it's printing the memory address where `list1` is stored. There isn't a special `println` for `List`s, you have to convert it to a String yourself. – Brad Mace Aug 16 '13 at 03:16
  • 1
    @kjm See the demo in @dasblinkenlight's answer where he uses a `for` loop to iterate over the elements. – squiguy Aug 16 '13 at 03:18
  • @kjm See [this post](http://stackoverflow.com/questions/8410294/why-does-printlnarray-have-strange-output-ljava-lang-string3e25a5) about printing the contents of arrays if you're interested. – Paul Bellora Aug 16 '13 at 03:51
0

They aren't being accepted because you are explicitly stating that your ArrayList is going to hold String arrays, and it appears you are passing in elements from String arrays as opposed to the entire array. Instead of adding an element from the array, try adding the entire array:

list1.add(s1)

Josh M
  • 11,611
  • 7
  • 39
  • 49
-1

Try this. Create ArrayList of objects and then assin complete string.

ArrayList<Object> list = new ArrayList<Object>();       
    String s1[] = new String[1];
    String s3[] = new String[3];

    s1[0]="Mary";
    s3[0]="Martha";
    s3[1]="Maggie";
s3[2]="Molly";

list.add(s1);
sanky jain
  • 873
  • 1
  • 6
  • 14
-3
ArrayList<String> Jobs = new ArrayList<String>();    


String programmer = "programmer";
Jobs.add(programmer);


for(String AllJobs : Jobs){
    System.out.println(AllJobs);
}
}//array list //java code
//try this
  • 4
    Please re-read the question, since you've missed what OP asked about. And don't write "code only" answers. Explain your code and why it solves the question. – Tom Jul 16 '17 at 18:45