for each循環還是第一次見,“java SE 5.0增加了一種功能很強的循環結構,可以用來一次處理數組中的每個元素(其他類型的元素集合亦可)而不必為指定下標值而分心”。
這種增強的for each循環的語句格式為:
for(variable : collection)statement
定義一個變量用於暫存集合的每一個元素,並執行相應的語句。collection這一集合表達式必須是一個數組或者是一個實現了Iterable接口的類對象(先不管這個Iterable)。
例如:
for(int element : a)//int element 其中的element相當於 for中的i,int是element的數據類型(我的個人理解不知道對不對~~)
System.out.println(element);
相當於:
for(int i=0;i<a.length;i++)
System.out.println(a[i]);//int element 其中的element相當於 for中的i,
打印數組a的每一個元素,一個元素占一行。這個循環可以讀作“循環a中的每一個元素”(element是元素的意思),再來一個具體例子來看看。
這個是書中的例子,直接貼出來
1 import java.util.*; 2 3 /** 4 * This program tests the Employee class. 5 * @version 1.11 2004-02-19 6 * @author Cay Horstmann 7 */ 8 public class EmployeeTest 9 { 10 public static void main(String[] args) 11 { 12 // fill the staff array with three Employee objects 13 Employee[] staff = new Employee[3]; 14 15 staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); 16 staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); 17 staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); 18 19 // raise everyone's salary by 5% 20 for (Employee e : staff) 21 e.raiseSalary(5); 22 23 // print out information about all Employee objects 24 for (Employee e : staff) 25 System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" 26 + e.getHireDay()); 27 } 28 } 29 30 class Employee 31 { 32 public Employee(String n, double s, int year, int month, int day) 33 { 34 name = n; 35 salary = s; 36 GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); 37 // GregorianCalendar uses 0 for January 38 hireDay = calendar.getTime(); 39 } 40 41 public String getName() 42 { 43 return name; 44 } 45 46 public double getSalary() 47 { 48 return salary; 49 } 50 51 public Date getHireDay() 52 { 53 return hireDay; 54 } 55 56 public void raiseSalary(double byPercent) 57 { 58 double raise = salary * byPercent / 100; 59 salary += raise; 60 } 61 62 private String name; 63 private double salary; 64 private Date hireDay; 65 }
20 and 24 行的代碼,for(Employee e :staff)其中的e是Employee的新對象,是嗎?這兩個for each循環改成for循環應該是什么??請各位大牛給看看~~~
小弟自己改一下:
for(int i=0;i<staff.length;i++)
{
staff[i].raiseSalary(6);
System.out.println("name=" + staff[i].getName() + ",salary=" + staff[i].getSalary() + ",hireDay="
+ staff[i].getHireDay());
}輸出的結果一樣,不知道對不對~~~~ 請各位大牛指教