Print a string from ArrayList of String[]?

user961627 picture user961627 · Oct 6, 2011 · Viewed 36.1k times · Source

I have an ArrayList full of strings arrays that I built like this:

String[] words = new String[tokens.length];

I have three arrays like above in my ArrayList:

surroundingWords.add(words);
surroundingWords.add(words1);
surroundingWords.add(words2);

etc

Now if I want to print out the elements in the String arrays within surroundingWords... I can't. The closest I can get to displaying the contents of the String[] arrays is their addresses:

[Ljava.lang.String;@1888759
[Ljava.lang.String;@6e1408
[Ljava.lang.String;@e53108

I've tried a lot of different versions of what seems to be the same thing, the last try was:

for (int i = 0; i < surroudingWords.size(); i++) {
        String[] strings = surroundingWords.get(i);
        for (int j = 0; j < strings.length; j++) {
            System.out.print(strings[j] + " ");
        }
        System.out.println();
    }

I can't get past this because of incompatible types:

found   : java.lang.Object
required: java.lang.String[]
                String[] strings = surroundingWords.get(i);
                                                       ^

Help!

I've already tried the solutions here: Print and access List

Answer

Tarc&#237;sio J&#250;nior picture Tarcísio Júnior · Oct 6, 2011

Try something like this

public class Snippet {
    public static void main(String[] args) {
        List<String[]> lst = new ArrayList<String[]>();

        lst.add(new String[] {"a", "b", "c"});
        lst.add(new String[] {"1", "2", "3"});
        lst.add(new String[] {"#", "@", "!"});

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

}