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

2 Answers 2

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

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

1 Comment

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

3 Comments

The ArrayList<String[]> is the current "correct" way of doing it.
@Kurtis: Unless you're stuck in Pre-1.5 land
@Poindexter True, that's why I said current correct way :)

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.