I need to declare a new array every iteration of the loop, I understand I can do it the following way:
//Store mappings from array name (String) to int arrays (int[])
Map<String, int[]> namedArrays = new HashMap<String, int[]>();
for (int i = 0; i < 3; i++)
{
//This is going to be the name of your new array
String arrayName = String.valueOf(i);
//Map an new int[] to this name
namedArrays.put(arrayName, new int[3]);
}
//If you need to access array called "2" do
int[] array2 = namedArrays.get("2");
My question is at the part where I declare a new array, what if have a array already named ai[],can I initialize it directly like this?:
namedArrays.put(arrayName,ai);
I tried this but I am getting an error.
EDIT: Now I understand I actually have a problem with retrieving the array I initialized the following way.
Map<String, int[]> namedArrays = new HashMap<String, int[]>();
for(int i=0;i<testCase;i++){
int num=scanner.nextInt();
int[] ai=new int[num];
for(int j=0;j<num;j++){
ai[j]=scanner.nextInt();
}
String arrayName = String.valueOf(i);
namedArrays.put(arrayName,ai);
I am trying to retrieve it the following way
for(int i=0;i<testCase;i++){
int[] array2 = namedArrays.get(i);
array2 contains value something like "[I@1fc4bec". But it is supposed to contain an array.
EDIT 2 : I understood that I can get the array the following way
String arrayName = String.valueOf(i);
// System.out.println(namedArrays.get(arrayName)[0]);
int b=namedArrays.get(arrayName).length;
int[] array2=new int[b];
for(int z=0;z<b;z++){
array2[z] = namedArrays.get(arrayName)[z];}
But y does
array2[z] = namedArrays.get(arrayName)
return "[I@1fc4bec" ?