我有一个四维数组,其中有一组静态值。但是我的问题是我想从api中获取一些数据,并且必须在运行时期间将其放入四维数组。我不知道该怎么做。任何微小的想法都会很感激。下面是我的示例,它显示了我的四维数组的静态定义。
static final String listdesc[][][][] =
{
{ // grey
{ // lightgray
{ "grey", "grey only" },
{ "lightgrey","#D3D3D3" },
{ "dimgrey","#696969" }
},
{ // darkgray
{ "grey", "darkgrey" },
{ "sgi grey 92","#EAEAEA" }
}
},
{ // blue
{ // lightblue
{ "blue", "lightblue" },
{ "dodgerblue 2","#1C86EE" }
},
{ // darkblue
{ "blue", "darkblue" },
{ "steelblue 2","#5CACEE" },
{ "powderblue","#B0E0E6" }
}
},
{ // yellow
{ // lightyellow
{ "yellow", "lightyellow" },
{ "yellow 1","#FFFF00" },
{ "gold 1","#FFD700" }
},
{ // darkyellow
{ "yellow", "darkyellow" },
{ "darkgoldenrod 1","#FFB90F" }
}
},
{ // red
{ // lightred
{ "red", "lightred" },
{ "indianred 1","#FF6A6A" }
},
{ // darkred
{ "red", "darkred" },
{ "firebrick 1","#FF3030" },
{ "maroon","#800000" }
},
}
};
这叫做primitive obsession code smell
。你应该用适当的数据结构和API来替换4d字符串数组来创建它:
ColorsData data = new ColorsData();
ColorSection section = data.addSection("gray");
section.setLightColors(
"grey only",
Color.create("lightgray", "#D3D3D3"),
Color.create("dimgray", "#696969"))
section.setDarkColors(
"darkgray",
Color.create("sgi grey 92", "#EAEAEA")
);
section = data.addSection("blue")
...
在AsyncTask
/background中获取数据,并在postExecute
中分配数据。
listdesc[][][][];
for (int i=0; i<listdesc.length; i++) {
for (int j=0; j<listdesc[i].length; j++) {
for (int k=0; k<listdesc[i][j].length; k++) {
for (int m=0; m<listdesc[i][j][k].length; m++) {
// populate with values
}
}
}
}
公共类{
public static void main(String[] args)
{
Random r = new Random();
int [][][][] a = new int[r.nextInt(10)+1][][][];
for(int i=0;i<a.length;i++)
{
a[i] = new int [(r.nextInt(5)+1)][][];
for(int j=0;j<a[i].length;j++)
{
a[i][j] = new int[(r.nextInt(5)+1)][];
for(int k=0;k<a[i][j].length;k++)
{
a[i][j][k] = new int [(r.nextInt(5)+1)];
for(int l=0;l<a[i][j][k].length;l++)
{
a[i][j][k][l] = r.nextInt(101)+100;
}
}
}
}
for(int i=0;i<a.length;i++)
{
System.out.println("3D #"+i);
for(int j=0;j<a[i].length;j++)
{
System.out.println("2D #"+j);
for(int k=0;k<a[i][j].length;k++)
{
System.out.println("1D #"+k);
for(int l=0;l<a[i][j][k].length;l++)
{
System.out.print(a[i][j][k][l] + " ");
}
System.out.println();
}
System.out.println();
}
System.out.println();
}
System.out.println();
}