int[] answer= new int[map.size()];
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int j=0; j<answer.length;j++){
int x=map.get(keys.get(j));
answer[j]=x;
}
return answer
When I print x
using System.out.println(x)
in the loop, I get values of 1, 2, 3
but when I return the answer and print it, I get [I@9826ac5
. Any idea why?
Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.
I[
is kind of the "class type" for an array of integer. Printing out this array itself will print the class type @
then a short hex string because that's the hash code of the array. It's the same as something you've probably seen like Object@0b1ac20
. This is implemented as the default toString()
for Object
.
Maybe you want to return a specific element of the array or print the whole array using a for loop?
Long story short, you can't easily print an array in java. Do this:
System.out.println( Arrays.toString(answer) );
because that is how array's toString()
method is implemented
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With