Re: reverse an array
zero wrote:
Hi everyone,
I'm trying to reverse an array of bytes using Collections.reverse:
<code>
byte[] theBytes = { 1, 2, 3 };
System.out.println( Arrays.toString( theBytes ) );
Collections.reverse( Arrays.asList( theBytes ) );
System.out.println( Arrays.toString( theBytes ) );
</code>
However, his prints
[1, 2, 3]
[1, 2, 3]
ie, the array is not reversed at all. When however I do the exact
same thing with a String array, it works:
<code>
String[] theStrings = { "Hello", "World" };
System.out.println( Arrays.toString( theStrings ) );
Collections.reverse( Arrays.asList( theStrings ) );
System.out.println( Arrays.toString( theStrings ) );
</code>
This gives the (expected) output:
[Hello, World]
[World, Hello]
What am I missing here?
Arrays.asList() taken an object arry, not an array of scalars. Your program
doesn't even compile in JDK 1.4.
What's happening is apparently that, since theBytes is not the right sort of
array to be the argument to asList, variable-length argument semantics are
being applied, as if you'd coded
Arrays.asList(o, p, q, r, s);
This would construct an array and then call the method, as if you'd coded
Object[] arr = new Object[] {o, p, q, r, s};
Arays.asList(arr);
Similarly, your code becomes (effectively)
Object[] arr = new Object[] {theBytes};
Arrays.asList(arr);
Obviously, sorting a one-member array won't do much.
You've found something truly ugly, by the way. In 1.4, the compiler
correctly tells you that Arrays.asList can't be applied to an array of
scalars. In 1.5, it silently does the wrong thing.