6

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

Community
  • 1
  • 1
user961627
  • 12,379
  • 42
  • 136
  • 210

2 Answers2

10

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

}
Tarcísio Júnior
  • 1,239
  • 7
  • 15
  • 2
    +1, this is the simplest an most "Java way" to go. The person asking the question should try and learn the behaviour of such java fundamentals as Object.toString() and Arrays / Collections helper classes – Shivan Dragon Oct 06 '11 at 15:36
4

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().

Poindexter
  • 2,396
  • 16
  • 19