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

3
  • your printing binary information. You'll need to convert each entry in the array to ascii before your print. Commented Apr 11, 2012 at 20:17
  • stackoverflow.com/questions/2137755/… Commented Apr 11, 2012 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? Commented Apr 11, 2012 at 20:21

4 Answers 4

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

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

Comments

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,

Comments

1

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

for(int i: reverse(number)){
  System.out.println(i);
}

Comments

1

Commons.lang

ArrayUtils.reverse(int[] array)

Done.

Comments

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.