Assign data to a four Dimensional Array at RunTime
I have a four dimensional array for which I have a static set of values. But my problem is I want to fetch some data from api and have to put it into the fo开发者_Python百科ur dimensional array during runtime. I am not sure how to do this. Any slightest idea will be appreciated. Here is my sample which shows my static definition of my four dimensional array.
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" }
},
}
};
This is called primitive obsession code smell
. You should replace 4d string array with a proper data structure and API to create it:
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")
...
Fetch data in AsyncTask
/background and assign it in postExecute
do this.
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 class Source {
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();
}
精彩评论