I'm new in Java and I have to solve this exercise. I have this code:
public class StringList {
private String list = "";
public StringList(String... str) {
for (String s : str) list += s+"\t";
}
}
and I have to change the class so that its objects allow the iteration by using this instruction:
for (String s : new StringList("a", "b", "c")) System.out.println(s);
My idea was to create a List and iterate on it. So I changed the code in this way:
public class StringList {
private List<String> list = new ArrayList<String>();
public StringList(String... str) {
for (String s: str) list.add(s);
}
}
but when I try the iteration with the above instruction I get this error (Can only iterate over an array or an instance of java.lang.Iterable) and I spent hours trying to fix it but I keep failing. Any help?
StringList
should implementIterable<String>
.