我们如何在Java中实现自定义可迭代对象?

2023年 8月 29日 27.8k 0

我们如何在Java中实现自定义可迭代对象?

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.

Syntax

public interface Iterable

登录后复制

import static java.lang.String.format;
import java.util.*;
// Person class
class 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%stLast Name:t%stAge:t%d", firstName, lastName, age);
}
}
// PersonArrayList class
public class PersonArrayList implements Iterable {
private List persons;
private static final int MIN_AGE = 10;
public PersonArrayList() {
persons = new ArrayList(MIN_AGE);
}
public PersonArrayList(int age) {
persons = new ArrayList(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 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: 20
First Name: Jai Last Name: Dev Age: 30

登录后复制

以上就是我们如何在Java中实现自定义可迭代对象?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论