简体   繁体   English

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

[英]Java - Enhanced for loop for ArrayList with custom object

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 Loop而不是下面代码中编写的常规For Loop方法?

Student.java 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;
  }
}

Here is the SudentList Class with Main Method 这是带有Main方法的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());
    }
  }
}

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()将其替换为直接对象引用就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM