好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java foreach循环为什么不能赋值的讲解

foreach循环为什么不能赋值

直接上代码

?

1

2

3

4

5

6

7

8

public class test4 {

     public static void main(String args[]){

         int [] a= new int [ 3 ];

         for ( int j:a){

             j= 55 ;

         }

     }

}

代码很简单

下面是java编译后的字节码

?

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

public class test4 {

   public test4();

     Code:

        0 : aload_0

        1 : invokespecial # 8                   // Method java/lang/Object."<init>":()V

        4 : return

   public static void main(java.lang.String[]);

     Code:

        0 : iconst_3          //将int型3推送至栈顶

        1 : newarray       int         //创建一个指定原始类型的数组,并将其引用值压入栈顶

        3 : astore_1          //将栈顶引用型数值存入第二个本地变量

        4 : aload_1           //将第二个引用类型本地变量推送至栈顶

        5 : dup               //复制栈顶数值并将复制值压入栈顶

        6 : astore        5        //将栈顶引用型数值存入指定本地变量,此处将数组引用放在第六个本地变量里

        8 : arraylength           //获得数组的长度值并压入栈顶

        9 : istore        4        //将栈顶int型数值存入指定本地变量。

       11 : iconst_0          //将int型0推送至栈顶

       12 : istore_3          //将栈顶int型数值存入第四个本地变量

       13 : goto           27       //跳转到27

       16 : aload         5        //将指定的引用类型本地变量推送至栈顶

       18 : iload_3           //将第四个int型本地变量推送值栈顶

       19 : iaload            //将int型数组指定索引的值推送至栈顶   

       20 : istore_2          //将栈顶int型数值存入第三个本地变量

       21 : bipush        55       //将单字节的常量值(-127~128)推送至栈顶

       23 : istore_2          //将栈顶int型数值存入第三个本地变量

       24 : iinc          3 , 1         //将指定int型变量增加指定值

       27 : iload_3           //将第四个int型本地变量推送至栈顶

       28 : iload         4        //将指定的int型本地变量推送至栈顶

       30 : if_icmplt     16       //比较栈顶两int型数值的大小,当结果小小于0时跳转

       33 : return             //从当前方法返回void

}

我们只需要关注6,16~23行就可以,可以发现这几句代码是将数组引用副本中的值取出放在栈顶,然后从栈顶取出变量放在本地变量3中,然后把55放在栈顶,再把55取出放在本地变量3中,从始至终的操作都是在本地局部变量中的,并没有对原来的数值产生任何影响。

foreach循环赋值问题

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

foreach ($list as $key=>$val){

     $data=array(); //这一个一定要加上不然循环后,modify_one,modify_two都会赋值

     if ($val[ 'id' ]!= 1 ){

         $link = explode( "801" ,$val[ 'p_link' ]);

         if (isset($link[ '1' ])){

             if ($val[ 'times' ]% 2 == 0 ){

                 $data[ 'modify_two' ]=$ftp->time($link[ '1' ]);

             } else {

                 $data[ 'modify_one' ]=$ftp->time($link[ '1' ]);

             }

             $admin->edit_modify($val[ 'id' ],$data);

             $admin->addTimes($val[ 'id' ]);

         }

     }

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/kakaxiaoxing/article/details/46680929

查看更多关于java foreach循环为什么不能赋值的讲解的详细内容...

  阅读:25次