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?

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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 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.
@kjm See the demo in @dasblinkenlight's answer where he uses a for loop to iterate over the elements.
@kjm See this post about printing the contents of arrays if you're interested.
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)

Comments

-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);

Comments

-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

1 Comment

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.

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.