Search code examples
javaarraysstringarraylistdereference

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


Solution

  • Cast the Object into a String[]:

    String[] strings = (String[]) surroundingWords.get(i);

    or use a parameterized ArrayList:

    ArrayList<String[]> surroundingWords = new ArrayList<String[]>();

    Then you won't have to cast the return value from get().