Reputation: 881
Just curious, but when I try to use this to reverse an array it always spits out some incoherent gibberish instead of the array reversed, such as [I@43256ea2
. Any ideas as to why it does this?
public class Fiddle {
public static void main(String[] args) {
int[] number = {1,2,3,4,5};
System.out.println(reverse(number));
}
public static int[] reverse(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[a.length-1-i] = a[i];
}
return b;
}
}
Thanks for any ideas as to why this is happening (it's probably because I'm forgetting something though).
Upvotes: 1
Views: 2818
Reputation: 81074
Use the utility method java.util.Arrays.toString(int[])
:
System.out.println(Arrays.toString(reverse(number)));
Array classes do not override Object.toString()
, meaning they use the default implementation provided by Object, which is "type@hashcode_in_hex
". The String representation of the type int[]
is [I
, which is why you are seeing this "incoherent gibberish."
Upvotes: 10
Reputation: 2311
You are printing the hash of the array. you should do something like
for(int i: reverse(number)){
System.out.println(i);
}
Upvotes: 1
Reputation: 425003
Try this:
System.out.println(Arrays.toString(reverse(number)));
It's one of the "mistakes" of java - you have to use Arrays.toString()
otherwise you get the default toString()
from Object
, which produces output like you're seeing,
Upvotes: 2