-2

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?

4
  • Please use Iterator.....
    – Amit
    Commented Jun 6, 2018 at 11:19
  • try google it first. (examples.javacodegeeks.com/core-java/util/iterator/…)
    – Michal
    Commented Jun 6, 2018 at 11:19
  • 4
    StringList should implement Iterable<String>.
    – Eran
    Commented Jun 6, 2018 at 11:20
  • why does everyone have started thinking that this is a tutoronline site?
    – Prashant
    Commented Jun 6, 2018 at 11:20

2 Answers 2

0

To do it the clean way, give a look at the java.lang.Iterable interface : https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html

If your StringList class implements it, then the instruction will work. I'll let you complete the exercise yourself though, but you can start with

public class StringList implements Iterable<String> {
    // the attribute you need to store the strings object

    // your constructor

    @Override
    public Iterator<String> iterator() {
        // This is what you need to fill
    }
}

PS : Using a list of string as an attribute is not a bad idea at all and will save you a lot of efforts and time, search what you can do with it

0

You have to implement Iterable<String> to your StringList like this:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;

public class StringList implements Iterable<String> {
    private List<String> list = new ArrayList<String>();

    public StringList(String... str) {
        for (String s: str) { list.add(s); }
    }

    @Override
    public Iterator<String> iterator() {
        return list.iterator();
    }

    @Override
    public void forEach(Consumer<? super String> action) {
        list.forEach(action);
    }

    @Override
    public Spliterator<String> spliterator() {
        return list.spliterator();
    }
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.