0
List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));

Basically I want an array of {a, b, c} however this isn't working. Do I have to iterate and load each element instead? How would I do this?

My error output looks like this:

[Ljava.lang.String;@3d4b7453
[Ljava.lang.String;@24c21495
5
  • @RohitJain edited with output message. Commented Oct 16, 2012 at 16:08
  • 5
    Those aren't errors, those are the string representations of the arrays. Commented Oct 16, 2012 at 16:08
  • Not sure I am following, if you want array {a,b,c} what is the List for? Are you trying deliberately to populate the list with arrays? Commented Oct 16, 2012 at 16:08
  • 1
    @meiryo The code will work fine, and will give you a list with the specified array in it.. What did you expected? Commented Oct 16, 2012 at 16:10
  • @amit I have a bunch of strings with stuff like a b c. I want to loop through them and store it all in a list of arrays. Commented Oct 16, 2012 at 16:10

5 Answers 5

4

Your code works fine, but it looks like you're printing the wrong thing. Do this instead:

for (String[] strs : list) {
    System.out.println(Arrays.toString(strs));
}

Printing just an array will give you output like what you're seeing.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How do I reference the first element of an array in a list?
@meiryo list.get(0)[0] gives you the first element of the first array in the list.
1

Try

List<String[]> list = new ArrayList<String[]>();
String str = "a b c";
list.add(str.split(" "));
System.out.println(Arrays.toString(list.get(0)));

Comments

1

I think you want to print this way: -

    List<String[]> list = new ArrayList<String[]>();
    String str = "a b c";
    list.add(str.split(" "));

    System.out.println(Arrays.toString(list.get(0)));

This prints: - [a, b, c]

Comments

1

You could use Arrays.toString() to print elements of an array,

System.out.println(Arrays.toString(list.get(0)));

or alternatively iterate over them:

for(String s : list.get(0)) System.out.println(s);

Comments

0

You can use Arrays.asList()

List<String> list = new ArrayList<String>();
String str = "a b c";
list.addAll(Arrays.asList(str.split(" ")));

To print the result is like:

for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

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.