19、foreach循环、可变参数和静态导入

学习目标:

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 = { 12345678910 };

 

        System.out.println(cal.sum(nums));

 

         

        System.out.println(cal.sum1());//可以没有参数

        //也可以是任意多个参数

        System.out.println(cal.sum1(2,3,4));

        System.out.println(cal.sum1(123456));

 

    }

 

}

三、静态导入

要使用用静态成员(方法和变量)我们必须给出提供这个方法的类。使用静态导入可以使被导入类的所有静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。不过,过度使用这个特性也会一定程度上降低代码地可读性。其实我个人对静态导入并不推荐使用,不过作为学习倒是可以学习一下。示例代码如下:

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));

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值