0

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" ?

4
  • 2
    Please provide the error message (in essence: visit the help center and read about "how to write up my-code-isnt-working" questions) Commented Jul 4, 2016 at 10:51
  • 2
    How about you show us the code you are having trouble with instead of the code you are not having trouble with? Commented Jul 4, 2016 at 10:52
  • "ai" is an array i get from user as an input. My question is 'is it necessary to create a new array' . And am not actually getting any array, but when i try to access array like this "int[] array2 = namedArrays.get("2");" array2 is null. Commented Jul 4, 2016 at 14:45
  • BTW "[I@1fc4bec" is the internal object name of an int-array. If you want to show the values, use Arrays.toString(array2); Commented Jul 4, 2016 at 15:44

5 Answers 5

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?

You can do it as you asked, but it won't work like you're expecting it to. When you pass the array into that function, you're actually passing a reference to the same array every time. What that means is if you get the array that's linked to the name "1" and modify it, you'll also be modifying the arrays for "2" and "3" and so on.

array2 contains value something like "[I@1fc4bec". But it is supposed to contain an array.

So, what's happened here is you've done something like this

int[] array2 = namedArrays.get(i);
System.out.println(array2);

The issue is that System.out.println() takes a String parameter, and int[] isn't a string. To get around this, Java calls toString() on your array before passing it to the real print function. It looks something like this:

public void println(int[] toPrint) {
    println("[I@" + Integer.toHexString(toPrint.hashCode()));
}

And, indeed, if you write that exact line with the "[I@" + Integer.toHexString(array2.hashCode(), you'll notice it'll print the exact same as if you just print the array2 itself.

As for the "[I" bit, that's actually Java assembly telling you the type of the object. [ means it's an array, I means it's an integer.

If you want to print the contents of the array, you should instead use System.out.println(Arrays.toString(array2)). Arrays.toString(int[]) converts the contents of an integer array to a nicely formatted String you can just print.

One last thing:
You seem to be essentially emulating a 2D array with a Map. If you just want 3 arrays, each of length 3, then you can write

int[][] array2D = new int[3][3];

and then you can refer to the arrays like so

System.out.println(array2D[1][2]);

which will print out the third value of your second array (remembering that item 0 is the first item.

This has the added benefit that you don't have to initialise a load of arrays and make calls to `Map.put()', since the elements of the array are all initialised to their default value (for an int, 0).

Sign up to request clarification or add additional context in comments.

Comments

1

From javadoc:

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

So the answer is yes, you can explicitly put an object if you know the key. If they already exists the value is replaced, otherwise is added.

Try with the following code:

String arrayName = "1";   // Any not null string works here
int[] ai = new int[0];    // any valid int[] works here
namedArrays.put(arrayName, ai);

Comments

0

Your Question is at the part where I declare a new array, What if have a array already named ai[] right ?

Answer is YES. why not. if ai[] is already you have then you can initialize map with this ai[] variable. but i will reccommend one check before initializing.

if(ai == null) //if ai referring to null 
    ai = new int[3]; // initialize with Array size of 3

Cross Check weather it is initialized or not ? to avoid NullPointerException further.

//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
    if(ai == null) //if ai refering to null
       ai = new int[3];
  namedArrays.put(arrayName, ai);
}

//If you need to access array called "2" do
int[] array2 = namedArrays.get("2");

1 Comment

When i do that i.e. initialize map with already declared array , and i try to access it ""int[] array2 = namedArrays.get("2") " am getting array2 as null.
0

So you need to init a map with empty arrays. Try streams - less code, easier to read, better compile and JIT optimisation.

final Map<String, int[]> namedArrays = IntStream.range(0, 3)
            .boxed()
            .collect(Collectors.toMap(i -> String.valueOf(i), i -> new int[3]));

An array object is just a link. You need to declare new one for each map entry. Otherwise all your keys in map will point to the same array.

Comments

-1
Try This


dictionary<string,int> namesarrays=new dictionary<string,int>();






{


for (int i = 0; i < namesarrays.Length; i++)


    {


  string res = namedArrays[i];




        Response.Write("<script> alert('" + HttpUtility.HtmlEncode(res) + "'); 

</script>");


    }

1 Comment

You might be suprised, but C# isn't Java, so your answer is not helpful here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.