Print string from ArrayList from string []?

I have an ArrayList full of string arrays that I created as follows:

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

There are three arrays in my ArrayList as above:

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

etc.

Now, if I want to print elements in String arrays inside surrounding words ... I cannot. The closest I can display the contents of the String [] array is their addresses:

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

I tried many different versions of what seems to be the same thing, the last attempt:

 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 due to incompatible types:

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

Help!

I already tried the solutions here: Print and access list

+6
source share
2 answers

Move Object to String[] :

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

or use a parameterized ArrayList:

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

Then you do not need to specify the return value from get() .

+4
source

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)); } } } 
+9
source

Source: https://habr.com/ru/post/898773/


All Articles