Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a string from ArrayList of String[]?

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

like image 744
user961627 Avatar asked Oct 06 '11 15:10

user961627


1 Answers

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

}
like image 120
Tarcísio Júnior Avatar answered Sep 24 '22 08:09

Tarcísio Júnior