1

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());
    }
  }
}
1
  • 1
    for(Student student : studentList){// code} means for each student in studentList... Commented Feb 10, 2018 at 12:53

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so in this case Java takes care of the studentList.get(i) part?
@Econ_newbie It works in a different by using Iterator. Read more at the link given
@Econ_newbie For details, see the Java Language Specification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.