Java相关,求教一个问题,如何遍历出list里的对象,然后调用那个对象的方法?

2024-11-29 12:34:08
推荐回答(3个)
回答1:

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 list = new ArrayList();
        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;
    }
}

回答2:

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 studentList = new ArrayList();
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;
}
}

回答3:

多贴点代码