1

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).

Battleroid
  • 861
  • 2
  • 14
  • 30
  • your printing binary information. You'll need to convert each entry in the array to ascii before your print. – Jonathan M Apr 11 '12 at 20:17
  • http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java – zod Apr 11 '12 at 20:19
  • Agreed -- but not immediately obvious to me why an array of {5,4,3,2,1} in memory would resolve to "[I@43256ea2". I'm imagining the bytes "00 00 00 05 00 00 00 04 00 00 00 03 etc...". Can anyone shed some light on why we see this specific output string? – Robert Martin Apr 11 '12 at 20:21

4 Answers4

10

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

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
2

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,

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

You are printing the hash of the array. you should do something like

for(int i: reverse(number)){
  System.out.println(i);
}
Simiil
  • 2,281
  • 1
  • 22
  • 32
1

Commons.lang

ArrayUtils.reverse(int[] array)

Done.

Ryan M.
  • 11
  • 2