Java相关,求教一个问题,如何遍历出list里的对象,然后调用那个对象的方法?
发布网友
发布时间:2022-05-02 17:01
我来回答
共3个回答
热心网友
时间:2023-10-09 00:52
import java.util.*;
// 测试方法
public class Main {
public static void main(String[] args){
Student student1 = new Student();
student1.setName("张三");
Student student2 = new Student();
student2.setName("李四");
Student student3 = new Student();
student3.setName("王五");
List<Student> list = new ArrayList<Student>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
for (Student student : list) {
System.out.println(student.getName());
}
// 或
// for (int i = 0; i < list.size; i++) {
// System.out.println(list.get(i).getName());
// }
}
}
// Student实体类
public class Student{
private String name;
public Student(){
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
追问不用反射吗?哎呀忘了那个什么情况了……楼下帮你修正了一下
热心网友
时间:2023-10-09 00:53
import java.util.ArrayList;
import java.util.List;
public class Test9 {
public static void main(String args[]){
Student s1 = new Student("tao");
Student s2 = new Student("li");
Student s3 = new Student("wu");
List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
for (Student student : studentList) {
System.out.println(student.getName());
}
}
}
class Student{
private String name;
public Student(String name){
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
热心网友
时间:2023-10-09 00:53
多贴点代码