在循环内创建最终变量 [英] creating final variables inside a loop

查看:113
本文介绍了在循环内创建最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许在java中使用:

is this allowed in java:

for(int i=0;i<5;i++){
  final int myFinalVariable = i;
}

我的问题的关键字是 final 。是否允许执行随循环的每次运行而变化的最终变量?我想知道这是因为final说你不能改变变量的值(只调用 myFinalVariable = i ),但是我用<$重新定义整个变量c $ c> final int 。

The keyword of my question is final. Is it allowed to do a final variable that changes with every run of the loop? I was wondering this because final says that you can't change the value of the variable (calling only myFinalVariable = i), but i'm redefining the whole variable with final int.

它们是两个完全不同的变量,只是具有相同的名称 - 上一次循环运行的变量已经向前往垃圾收集器了吗?

Are they two completely different variables just with the same name - with the variable from the previous run of the loop already heading down the road to the garbage collector?

推荐答案

是的,这是允许的。 final 关键字表示您无法更改其范围内的变量的值。对于循环示例,您可以将变量超出循环底部的范围,然后返回到范围,并在循环顶部添加新值。分配给循环中的变量将不起作用。

Yes, it is allowed. The final keyword means that you can't change the value of the variable within its scope. For your loop example, you can think of the variable going out of scope at the bottom of the loop, then coming back into scope with a new value at the top of the loop. Assigning to the variable within the loop won't work.

这篇关于在循环内创建最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆