Java - 使用自定义对象为ArrayList增强for循环

时间:2018-02-10 12:48:12

标签: java for-loop arraylist

给定带有ArrayList的StudentList类,它带有三个字段的学生对象:卷号,名称和标记,如何编写增强的For循环而不是常规For循环方法,如下面的代码所示?

Student.java

public class Student {
private int rollNumber;
private String name;
private int marks;

public Student(int roll, String name, int marks){
    this.rollNumber=roll;
    this.name=name;
    this.marks=marks;
}

public int getRollNumber(){
    return this.rollNumber;
}

public String getName() {
    return name;
}

public int getMarks() {
    return marks;
  }
}

这是带主要方法的SudentList类

StudentList.java

import java.util.ArrayList;
import java.util.List;

public class StudentList {
public static void main(String[] args) {

Student a = new Student(1, "Mark", 80);
Student b = new Student(2, "Kevin", 85);
Student c = new Student(3, "Richard", 90);

List<Student> studentList = new ArrayList<>();
studentList.add(a);
studentList.add(b);
studentList.add(c);

for (int i = 0; i < studentList.size(); i++) {
  System.out.println("Roll number: " + 
  studentList.get(i).getRollNumber() +
                ", Name: " + studentList.get(i).getName() + ", Marks: " + 
  studentList.get(i).getMarks());
    }
  }
}

1 个答案:

答案 0 :(得分:3)

foreach代替索引,为您提供直接对象

for (Student st : studentList) {
       System.out.println("Roll number: " +  st.getRollNumber() + ", Name: " + st.getName() + ", Marks: " + st.getMarks());
    }

因此,每当您看到list.get()替换为直接对象引用时,您就完成了。