简体   繁体   English

我应该在类中使用final静态变量还是在static方法中使用final变量

[英]Should I prefer final static variable inside class or final variable inside a static method

Provided the final variable is used only inside one static method , should I declare it as final static member in class, or final variable in the static method. 如果最终变量仅在一个静态方法中使用 ,我应该将其声明为类中的最终静态成员,还是在静态方法中声明为最终变量。

If it is declared inside method, will it be initialized each time the function is called. 如果在方法内部声明,则每次调用该函数时都会对其进行初始化。 (function is invoked a lot of times) (函数被多次调用)

EDIT: The Variable is a List initialized using Arrays.asList(...) function 编辑:变量是使用Arrays.asList(...)函数初始化的List

If it is declared inside method, will it be initialized each time the function is called. 如果在方法内部声明,则每次调用该函数时都会对其进行初始化。 (function is invoked a lot of times) (函数被多次调用)

Yes. 是。 If you declare your variable inside the method, it will invoke Arrays.asList(...) each time the method is invoked. 如果在方法内部声明变量,则每次调用该方法时,它将调用Arrays.asList(...)

If your variable has a costly initialization and/or the method is invoked a lot of times you should declare it as a private static final field. 如果您的变量进行了昂贵的初始化和/或多次调用了该方法,则应将其声明为private static final字段。

Ideally you'd want it to be a static final in the method itself. 理想情况下,您希望它是方法本身的static final But Java does not support that. 但是Java不支持。 (C++ does by the way). (C ++顺便说一句)。

Unless the variable is a reference to an object that has startup overhead, I'd keep it as local as possible and write final in the method, rather than pollute the class namespace with a final static that's only used in one function. 除非变量是对具有启动开销的对象的引用,否则我将使其尽可能保持局部并在方法中写入final ,而不是使用仅在一个函数中使用的final static变量污染类名称空间。 I'd trust the compiler to make any optimisations. 我相信编译器可以进行任何优化。 Alternatively, create an inner class and declare it there. 或者,创建一个内部类并在那里声明它。

Yes, final static can be used. 是的,可以使用final static值。 The element will initialize only once: at time of class loading. 该元素仅初始化一次:在加载类时。 You can use this any number of times. 您可以多次使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM