0

I am looking for a method to reverse an array of chars.

If I use an ArrayList<Character> to store my chars, I can use the Collections.reverse(List<T>)-method.

List<Character> list = new ArrayList<>();
for (int i = 0; i < 26; i++) {
  list.add((char) (97 + i));
}
Collections.reverse(list);

But how can I reverse an array of chars? Is there any API-method or do I have to implement it by myself? Collections.reverse(Arrays.asList(char[])) is useless.

char[] input = {'a', 'b', 'c', 'd', 'e'};
char[] out = new char[input.length];
for (int i = 0; i < input.length; i++) {
  out[i] = input[input.length-i-1];
}

Thanks.

0xf10
  • 108
  • 1
  • 11
  • how abt just write a simple reverse method? it is just a for loop – Mox Apr 18 '17 at 14:08
  • 1
    Why not loop from `input.length -1` till 0 instead of reversing array? – SMA Apr 18 '17 at 14:09
  • 2
    `char[] input = { 'a', 'b', 'c', 'd', 'e' }; String s = new StringBuilder(new String(input)).reverse().toString(); char[] out = s.toCharArray();` – ShahzadIftikhar Apr 18 '17 at 14:19
  • premature duplicate close: the OP asked for a reversal of chars based on *JDK methods*. 0xflotus: nice solution provided by @ShahzadIftikhar – wero Apr 18 '17 at 14:21
  • @wero Exactly! This is quite different from that. – ShahzadIftikhar Apr 18 '17 at 14:22
  • I found a `reverse(char[])`-method for `array`s in class `ArrayUtils` in the Apache Commons Lang. This is also a good option. – 0xf10 Apr 18 '17 at 19:20

0 Answers0