[英]Can i define an final String[][] with some other final String[]s?
我定義了一些最終的String數組並在另一個地方初始化它們,現在我想讓它更容易遍歷它們,所以也許我需要將它們放在最終的String [] []中,
private static final String[] a,b,c,d;
private static final String[][] all = {a,b,c,d};
但它給了我錯誤
The blank final field a may not have been initialized
現在我知道最終變量應該在使用之前分配,但我不知道解決我的問題,有沒有辦法遍歷a,b,c,d比下面的代碼更容易?
for(String s : a){};
for(String s : b){};
...
順便說一下,我想通過遍歷它們進行分配
只要您知道a
到d
的大小,就可以在聲明它們時初始化它們:
private static final String[] a = new String[YOUR_VALUE_HERE],
b = new String[YOUR_VALUE_HERE],
c = new String[YOUR_VALUE_HERE],
d = new String[YOUR_VALUE_HERE];
private static final String[][] all = {a,b,c,d};
您以后仍可以初始化數組的內容,因為只有數組引用本身才是最終的。
如果你想擁有靜態和最終數組,我建議你只使用帶有訪問器的singleton patten。 這樣你就有一個實例(靜態),那些數組不能在另一個實例上更改(最終)。
public class ArrayContainer {
private ArrayContainer instance = new ArrayContainer();
private static final int SIZE_A = 1;
private static final int SIZE_B = 2;
private static final int SIZE_C = 3;
private static final int SIZE_D = 4;
private static String[] a, b, c, d;
private static String[][] all;
private ArrayContainer() {
a = new String[SIZE_A];
b = new String[SIZE_B];
c = new String[SIZE_C];
d = new String[SIZE_D];
all = new String[][]{a, b, c, d};
}
public String[] getA(){
return a;
}
public String[] getB(){
return b;
}
public String[] getC(){
return c;
}
public String[] getD(){
return d;
}
public String[][] getAll(){
return all;
}
}
無論如何你應該記住,最終數組不是不可變的。 如果你想擁有不可變的我建議你讀一下: Java中的不可變數組 。
你仍然可以只添加吸氣劑
public String get(int array, int index){
return all[i][y];
}
如果需要初始化靜態字段,請使用靜態塊:
static final String[] a;
static {
// put all the logic here
// and assign final var at the end
a = new String[17];
}
static final String[][] all = {a};
還要記住,上面例子中的順序很重要。 聲明all
的初始化數組前a
會引起The blank final field a may not have been initialized
錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.