可以用来依次处理数组中的每个元素(其他类型的元素集合亦可)而不必为指定下标值而分心。
这种for循环的语句格式为:
for(variable:collection) statement
定义一个变量用于暂存集合中的每一个元素,并执行相应的语句或者语句块。集合表达式必须是一个数组或者是一个实现了iterable接口的类对象,比如arrayList。
例如:
for(int element:a)
Systm.out.println(element);
打印数组a的每一个元素,一个元素占一行。
如果不希望遍历整个集合,或者在循环内部需要操作下标值就需要使用传统的for循环。
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 }