java 返回 ArrayList<Teacher>示例
时间: 2023-02-12 14:33:22 浏览: 108
JAVA ArrayList详细介绍(示例)
```
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Teacher> teachers = new ArrayList<Teacher>();
teachers.add(new Teacher("John", "Smith"));
teachers.add(new Teacher("Jane", "Doe"));
teachers.add(new Teacher("Bob", "Johnson"));
for (Teacher teacher : teachers) {
System.out.println(teacher.getFirstName() + " " + teacher.getLastName());
}
}
}
class Teacher {
private String firstName;
private String lastName;
public Teacher(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
```
这是一个简单的示例,在这里,我们定义了一个Teacher类,并在main方法中创建了一个ArrayList来存储Teacher对象。我们在ArrayList中添加了三个Teacher对象,然后遍历ArrayList并打印出每个Teacher的firstName和lastName。
阅读全文