我知道干净的代码约定要求 Java 中的最终变量是 ALL_CAPS。但是如果我的变量是一个数组呢?必须全部大写吗?以下哪一项是最佳实践:
public static final String[] MY_ARRAY = {"A", "B"};
//...
String str = MY_ARRAY[0];
或者
public static final String[] myArray = {"A", "B"};
//...
String str = myArray[0];
最佳答案
据我所知,没有 Java 代码约定提倡所有 final 变量应该全部大写。 常量 应该全部大写,常量通常指的是不可变(或有意永不改变)的最终字段。
在这种情况下,您使用的是一个数组,并且由于它是公开的,所以很可能会发生变异。出于这个原因,我不会将其视为常量,因此使用 myArray
。
作为引用,这里引用了官方 Oracle Java 代码约定:
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores (“_”). (ANSI constants should be avoided, for ease of debugging.)
关于java最终数组小写或大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265964/