Java相关,求教一个问题,如何遍历出list里的对象,然后调用那个对象的方法?
可能说得不清楚,例如这样,我有个一个Student类,有Name属性,这个类有getName,setName方法,我实例化了3个Student类对象并给他们Name,然后...
可能说得不清楚,例如这样,我有个一个Student类,有Name属性,这个类有getName,setName方法,我实例化了3个Student类对象并给他们Name,然后我把他们放进一个list里(ArrayList对象),但是,我通过遍历,却不能取出它们的Name属性,请问如何做呢?
for(Student s : list){
System.out.println(s.getName());//不能取出Name属性
} 展开
for(Student s : list){
System.out.println(s.getName());//不能取出Name属性
} 展开
3个回答
展开全部
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;
}
}
追问
不用反射吗?哎呀忘了那个什么情况了……楼下帮你修正了一下
展开全部
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;
}
}
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;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
多贴点代码
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询