Java - 使用自定义对象增强了 ArrayList 的 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48720936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Enhanced for loop for ArrayList with custom object
提问by javaland235
Given this StudentList Class with ArrayList that takes Student Object with three fields: Roll number, Name and Marks, how to write enhanced For Loop instead of the regular For Loop method as written in the code below?
鉴于这个带有 ArrayList 的 StudentList 类采用具有三个字段的学生对象:卷号、名称和标记,如何编写增强的 For 循环而不是下面代码中编写的常规 For 循环方法?
Student.java
学生.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;
}
}
Here is the SudentList Class with Main Method
这是带有 Main 方法的 SudentList 类
StudentList.java
学生名单.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());
}
}
}
回答by Suresh Atta
Instead of index, foreach
gives you direct objects
foreach
为您提供直接对象而不是索引
for (Student st : studentList) {
System.out.println("Roll number: " + st.getRollNumber() + ", Name: " + st.getName() + ", Marks: " + st.getMarks());
}
So whenever you see list.get()
replace it with direct object reference and you are done.
所以每当你看到list.get()
用直接对象引用替换它时,你就完成了。