Possible Duplicate:
How do I reverse an int array in Java?
What is the equivalent function in java to perform Array.Reverse(bytearray) in C# ?
Integer reverseBytes() Method in Java The java. lang. Integer. reverseBytes(int a) is a built-in method which returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.
Efficient approach: The idea is to use shift operators only. Move the position of the last byte to the first byte using left shift operator(<<). Move the position of the first byte to the last byte using right shift operator(>>). Move the middle bytes using the combination of left shift and right shift operator.
public static void reverse(byte[] array) {
      if (array == null) {
          return;
      }
      int i = 0;
      int j = array.length - 1;
      byte tmp;
      while (j > i) {
          tmp = array[j];
          array[j] = array[i];
          array[i] = tmp;
          j--;
          i++;
      }
  }
                        You can use Collections.reverse on a list returned by Arrays.asList operated on an Array: -
    Byte[] byteArr = new Byte[5];
    byteArr[0] = 123; byteArr[1] = 45;
    byteArr[2] = 56;  byteArr[3] = 67;
    byteArr[4] = 89;
    List<Byte> byteList = Arrays.asList(byteArr); 
    Collections.reverse(byteList);  // Reversing list will also reverse the array
    System.out.println(byteList);
    System.out.println(Arrays.toString(byteArr));
OUTPUT: -
[89, 67, 56, 45, 123]
[89, 67, 56, 45, 123] 
UPDATE: -
Or, you can also use: Apache Commons ArrayUtils#reverse method, that directly operate on primitive type array: -
byte[] byteArr = new byte[5];
ArrayUtils.reverse(byteArr);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With