Re: reverse an array
On 20-8-2006 10:47, zero wrote:
Hi everyone,
I'm trying to reverse an array of bytes using Collections.reverse:
byte[] theBytes = { 1, 2, 3 };
System.out.println( Arrays.toString( theBytes ) );
Collections.reverse( Arrays.asList( theBytes ) );
System.out.println( Arrays.toString( theBytes ) );
[...]
String[] theStrings = { "Hello", "World" };
System.out.println( Arrays.toString( theStrings ) );
// similar to:
// System.out.println( Arrays.toString( "Hello", "World" ));
Collections.reverse( Arrays.asList( theStrings ) );
// similar to:
// Collections.reverse( Arrays.asList( "Hello", "World" ) );
System.out.println( Arrays.toString( theStrings ) );
[...]
What am I missing here?
The Arrays.toString and Arrays.asList methods take a variable number of
arguments (varargs) of *reference types*, not of primitive types.
Compare it with the following, except you had just one element in
theByteArrays:
byte[] theBytes = { 1, 2, 3 };
byte[] theBytes2 = { 4, 5, 6 };
Object[] theByteArrays = {theBytes, theBytes2};
System.out.println(Arrays.deepToString(theByteArrays));
// similar to:
// System.out.println(Arrays.deepToString(theBytes, theBytes2));
Collections.reverse(Arrays.asList(theByteArrays));
// similar to:
// Collections.reverse(Arrays.asList(theBytes, theBytes2));
System.out.println(Arrays.asList(theByteArrays).size());
System.out.println(Arrays.deepToString(theByteArrays));
And print the size of the lists:
System.out.println(Arrays.asList(theBytes).size());
System.out.println(Arrays.asList(theStrings).size());
--
Regards,
Roland