Java是否支持函数内部的静态变量来保持调用之间的值? [英] Does Java support static variables inside a function to keep values between invocations?

查看:177
本文介绍了Java是否支持函数内部的静态变量来保持调用之间的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://stackoverflow.com/a/572550/1165790

我想在Java中使用这个功能,因为我正在设计的函数很少被调用(但是当它被调用时,它会启动一个递归链),因此,我不想让变量变为每次实例化类时,实例字段都会浪费内存。

I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.

我也不想创建一个额外的参数,因为我不想加重对函数的外部调用有实现细节。

I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.

我尝试了static关键字,但Java说这是一个非法的修饰符。有直接替代方案吗?如果没有,建议采用哪种解决方法?

I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?

我希望它具有功能范围,而不是类范围。

I want it to have function scope, not class scope.

推荐答案


我希望它具有函数范围,而不是类范围。

I want it to have function scope, not class scope.

然后你运气不好。 Java提供 static (类作用域),实例和局部变量。没有Java等价于C的函数作用域 static 变量。

Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.

如果变量确实需要是静态的,那么你唯一的选择是使它成为类范围。这就是你所拥有的全部。

If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.

另一方面,如果这是一个在一些递归方法调用中使用的工作变量,那么将它设为静态将意味着你的算法不可重入。例如,如果您尝试在多个线程上运行它,它将崩溃,因为线程将全部尝试使用相同的静态...并相互干扰。在我看来,正确的解决方案是使用方法参数传递此状态。 (你也可以使用一个所谓的线程本地变量,但它们有一些重要的下行...如果你担心存储量大约是200字节的开销!)

On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)

这篇关于Java是否支持函数内部的静态变量来保持调用之间的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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