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是元素的意思),再來一個具體例子來看看。
這個是書中的例子,直接貼出來
import java.util.*; /** * This program tests the Employee class. * @version 1.11 2004-02-19 * @author Cay Horstmann */ public class EmployeeTest { public static void main(String[] args) { // fill the staff array with three Employee objects Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); // raise everyone's salary by 5% for (Employee e : staff) e.raiseSalary(5); // print out information about all Employee objects for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } class Employee { public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } private String name; private double salary; private Date hireDay; }
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());
}輸出的結果一樣,不知道對不對~~~~ 請各位大牛指教
轉自:http://www.cnblogs.com/jerry007/archive/2013/01/18/2866153.html