Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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);
share|improve this answer
    
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 3:13
    
@kjm it's printing the memory address where list1 is stored. There isn't a special println for Lists, you have to convert it to a String yourself. –  Brad Mace Aug 16 '13 at 3: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 3:18
    
@kjm See this post about printing the contents of arrays if you're interested. –  Paul Bellora Aug 16 '13 at 3:51

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)

share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.