学习目标:
1、掌握foreach循环
2、掌握可变参数的定义
3、掌握静态导入的使用
学习过程:
一、foreach循环
JDK1.5加入的增强for循环,称为foreach循环。语法格式如下:
for(ElementType element:arrayName){
…
//循环体
};
增强for(part1:part2){part3},part2中是一个数组对象,或者是带有泛性的集合。part1定义了一个局部变量,这个局部变量的类型与part2中的对象元素的类型是一致的。part3当然还是循环体。
示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Student stu1 = new Student(); stu1.setId( 1 ); stu1.setName( "刘德华" ); Student stu2 = new Student(); stu2.setId( 2 ); stu2.setName( "郭富城" ); Student stu3 = new Student(); stu3.setId( 3 ); stu3.setName( "张学友" ); ArrayList<Student> students= new ArrayList<Student>(); students.add(stu1); students.add(stu2); students.add(stu3); for (Student stu:students){ System.out.println(stu.getName()); } |
二、可变参数
可变参数使程序员可以声明一个接受可变数目参数的方法。注意,可变参数必须是函数声明中的最后一个参数。可变参数的参数名称和一个数组作为参数效果类似,但是变参与数组最大的区别在于变参可以没有参数。语法格式如下:
public void 方法名称(参数类型... 参数) {
}
你可以对比变参和数组之间的区别,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class Cal { public int sum( int [] nums) { int sum = 0 ; for ( int i : nums) { sum += i; } return sum; } // 可变参数你可以上面的数组作为参数对比一下。 public int sum1( int ... nums) { int sum = 0 ; for ( int i : nums) { sum += i; } return sum; } public static void main(String[] args) { Cal cal = new Cal(); int [] nums = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 }; System.out.println(cal.sum(nums)); System.out.println(cal.sum1()); //可以没有参数 //也可以是任意多个参数 System.out.println(cal.sum1( 2 , 3 , 4 )); System.out.println(cal.sum1( 1 , 2 , 3 , 4 , 5 , 6 )); } } |
三、静态导入
要使用用静态成员(方法和变量)我们必须给出提供这个方法的类。使用静态导入可以使被导入类的所有静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。不过,过度使用这个特性也会一定程度上降低代码地可读性。其实我个人对静态导入并不推荐使用,不过作为学习倒是可以学习一下。示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //静态导入。 import static java.lang.Math.*; public class Sta { public static void main(String[] args) { //以前必须使用类名访问静态方法和静态变量 System.out.println(Math.random()); //使用了静态导入后就可以直接使用该方法了。 System.out.println(abs(- 100 )); System.out.println(sin( 0.23 )); } } |