an iterable interface is defined in java.lang package and introduced with java 5 version. an object that implements this interface allows it to be the target of the for-each statement. this for-each loop is used for iterating over arrays and collections. an iterable interface can also be implemented to create custom behavior.
syntaxpublic interface iterable<t>
示例import static java.lang.string.format;import java.util.*;// person classclass person { private string firstname, lastname; private int age; public person(){ } public person(string firstname, string lastname, int age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } public string getfirstname() { return firstname; } public string getlastname() { return lastname; } public int getage() { return age; } public void setfirstname(string firstname) { this.firstname = firstname; } public void setlastname(string lastname) { this.lastname = lastname; } public void setage(int age) { this.age = age; } @override public string tostring() { return format("first name:\t%s\tlast name:\t%s\tage:\t%d", firstname, lastname, age); }}// personarraylist classpublic class personarraylist implements iterable<person> { private list<person> persons; private static final int min_age = 10; public personarraylist() { persons = new arraylist<person>(min_age); } public personarraylist(int age) { persons = new arraylist<person>(age); } public void addperson(person p) { persons.add(p); } public void removeperson(person p) { persons.remove(p); } public int age() { return persons.size(); } @override public iterator<person> iterator() { return persons.iterator(); } public static void main(string[] args) { person p1 = new person("adithya", "sai", 20); person p2 = new person("jai","dev", 30); personarraylist plist = new personarraylist(); plist.addperson(p1); plist.addperson(p2); for (person person : plist) { system.out.println(person); } }}
输出first name: adithya last name: sai age: 20first name: jai last name: dev age: 30
以上就是我们如何在java中实现自定义可迭代对象?的详细内容。