Battleroid
Battleroid

Reputation: 881

Reversing integer array

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

Answers (4)

Mark Peters
Mark Peters

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

Ryan M.
Ryan M.

Reputation: 11

Commons.lang

ArrayUtils.reverse(int[] array)

Done.

Upvotes: 1

Simiil
Simiil

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

Bohemian
Bohemian

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

Related Questions