JSTL - Using forEach to iterate over a user-defined class [duplicate]

守給你的承諾、 提交于 2019-11-30 13:57:01

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.

Yes, you should implement java.util.Iterable

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!