Java增强for循环编写求助:传统循环转增强循环报错问题
Hey there! I see exactly where you went wrong here—let's get this sorted out quickly.
The Root Cause of the Error
The error you're seeing happens because the enhanced for-loop (for-each loop) already gives you direct access to each Employee object in the list, so you don't need to call list.get() at all.
When you write for(Employee emp : list), the variable emp is already the current Employee element from the list. The get() method expects an integer index (like 0, 1, etc.), but you're passing an Employee object instead—that's why the compiler throws that "not applicable for the arguments (Employee)" error.
The Corrected Code
Here's how your method should look with the proper enhanced for-loop:
//display employees public void outputEmployee(ArrayList<Employee> list) { System.out.println("Employee ID" + "\t\t" + "Full Name" + "\t\t" + "Address" + "\t\t" + "Faculty Name" + "\t\t" + "Department" + "\t\t" + "Designation" + "\n"); System.out.println( "================================================================================================================" ); // Enhanced for-loop directly iterates over each Employee in the list for(Employee emp : list) { // No need for list.get(emp) — emp is already the Employee object we need System.out.println(emp.getEmployeeId() + "\t" + emp.getEmployeeFullName() + "\t\t" + emp.getEmployeeAddress() + "\t" + emp.getFacultyName() + "\t" + emp.getDepartment() + "\t" + emp.getEmployeeDesignation() + "\n"); System.out.println( "----------------------------------------------------------------------------------------------------------------" ); } }
A Quick Note on Enhanced For-Loops
Think of the enhanced for-loop as a shorthand that handles index tracking for you. It's perfect for when you just need to iterate through every element in a collection without needing to know the index of each element. If you ever do need the index (like for modifying elements in place), then the traditional for-loop makes more sense—but in this case, the enhanced loop is cleaner and simpler.
内容的提问来源于stack exchange,提问作者Escort Personal Adz

