javaland235
javaland235

Reputation: 803

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?

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

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());
    }
  }
}

Upvotes: 1

Views: 19993

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122008

Instead of index, foreach gives you direct objects

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.

Upvotes: 5

Related Questions