0

Today I had a strange experience when using a for loop in Java, which I really can't explain. That's my code snippet:

List<String[]> list;
....
for (String[] tmp : list.get(0)) {
...
}

This code snippet isn't compiling, because list.get(0) is returning a String an not an array of Strings. But why?

5 Answers 5

3

list.get(0) returns an array of Strings, so when you iterate over it, you are getting individual Strings:

for (String tmp : list.get(0)) {
...
}

If you iterate over the entire list, you will get a String array in each iteration:

for (String[] tmp : list) {
...
}
Sign up to request clarification or add additional context in comments.

1 Comment

It can be so simple: I really just had a error in reasoning. Thanks!
1

Try to iterate over arrays of string

for (String[] tmp : list) {
...
}

or to iterate over strings of first array

for (String tmp : list.get(0)) {
...
}

1 Comment

It can be so simple: I really just had a error in reasoning. Thanks!
0
for (String[] tmp : list.get(0))

should be

for (String tmp : list.get(0))

since list.get(0) is an array of strings, not array of string arrays.

1 Comment

It can be so simple: I really just had a error in reasoning. Thanks!
0

Actually, list.get(0) is not returning a String but a String[] as you expect. List<String[]> list is a List of String[]. list.get(0) therefore is a String[]. The problem is with your loop variable. If you loop over a String[], the type of the loop variable which holds a single element during the loop is just String.

It should be:

List<String[]> list;
// ...
for (String el : list.get(0)) {
    // ...
}

1 Comment

It can be so simple: I really just had a error in reasoning. Thanks!
0

When you are calling list.get(0), it is returning a String array. If I extend your code it becomes like below,

String[] strArr = list.get(0);

....
for (String[] tmp : strArr) { //compilation issue
...
}

Obviously which is wrong as each object inside strArr is String, not String array.

1 Comment

It can be so simple: I really just had a error in reasoning. Thanks!

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.