7

What methods do I need to add to a custom Java class so that I can iterate over the items in one of its members? I couldn't find any specifications about how the JSTL forEach tag actually works so I'm not sure how to implement this.

For example, if I made a generic "ProjectSet" class and I woud like to use the following markup in the JSP view:

<c:forEach items="${projectset}" var="project">
...
</c:forEach>

Basic class file:

public class ProjectSet {
    private ArrayList<Project> projects;
    public ProjectSet() {
        this.projects = new ArrayList<Project>();
    }
    // .. iteration methods ??
}

Is there any interface that I must implement like PHP's ArrayAccess or Iterator in order for this to work?

Edit: Without directly accessing the ArrayList itself, because I will likely be using some sort of Set class using generics, and the JSP view shouldn't have to know about the inner workings of the class.

Lotus Notes
  • 6,302
  • 7
  • 32
  • 47

3 Answers3

4

The Iterable interface provides this functionality:

public class ProjectSet implements Iterable<Project> {
    private ArrayList<Project> projects;
    public ProjectSet() {
        this.projects = new ArrayList<Project>();
    }

    // .. iteration methods ??
   @Override
   public Iterator<Project> iterator() {
       return projects.iterator();
   }
}

You can exchange the iterator logic as you need.

Dominik
  • 1,241
  • 1
  • 14
  • 31
  • 9
    Caveat to that is that JSTL forEach does not support iterable (extremely annoying) as forEach type. So you need to do ${projectSet.iterator()} – Adam Gent Feb 13 '11 at 15:16
  • 2
    Actually .iterator() will only work on the latest Servlet Container (and even the latest JSTL still does not support iterable). You will need to make a getter for the iterator ( getIterator() ). – Adam Gent Feb 14 '11 at 00:29
0

Yes, you should implement java.util.Iterable

Behrang
  • 46,888
  • 25
  • 118
  • 160
0

Unfortunately, the forEach tag does not support Iterable as the items source. It does support:

  • Arrays
  • Collection
  • Iterator
  • Enumeration
  • Map
  • Comma-separated list of values given in a String

(relevant source code: ForEachSupport)

Of these, it's probably best to use an Iterator as the forEach source when you wish to fetch items from your own class.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43