Why printing Java array shows memory location

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 a loop, I get the values 1, 2, 3 , but when I return the answer and print it, I get [ I@9826ac5 . Any idea why?

+4
source share
3 answers

I[ is a kind of class type for an integer array. A listing of this array will print the class type @ , and then a short sixth line, because this is the hash code of the array. This is the same as what you probably saw as Object@0b1ac20 . This is done by default toString() for Object .

Maybe you want to return a specific element of an array or print the entire array using a for loop?

+6
source

In short, you cannot easily print an array in java. Do it:

 System.out.println( Arrays.toString(answer) ); 
+3
source

because that's how the toString() method is implemented

+1
source

All Articles