How can I make my class iterable so I can use foreach syntax?

后端 未结 5 996
借酒劲吻你
借酒劲吻你 2020-12-16 10:33

I have Book and BookList classes. BookList is something like this:

public class BookList 
{
    private final List<         


        
5条回答
  •  無奈伤痛
    2020-12-16 11:14

    You need to implement the Iterable interface, which means you need to implement the iterator() method. In your case, this might look something like this:

    public class BookList implements Iterable {
        private final List bList = new ArrayList();
    
        @Override
        public Iterator iterator() {
            return bList.iterator();
        }
    
        ...
    }
    

提交回复
热议问题