6

Is it possible to cast an int array to a char array? If so - how?


I'm currently working on a project where I need to create an char array containing the alphabet. My current code creats an int array (which should be converted to an char array - in one Line!):

return IntStream.range('a', 'z' + 1).toArray();

TheRealVira
  • 1,444
  • 4
  • 16
  • 28
  • If you want to convert a digit (0-9), you can add 48 to it and cast, or something like `Character.forDigit(a, 10)`;. – Vishal Goyal Oct 07 '16 at 07:37
  • yes it is possible , just convert your number into 16 based number , consists of a-f and 0-9 :)) – Mohsen_Fatemi Oct 07 '16 at 07:52
  • 2
    No, you can't cast `int[]` to `char[]`. Also, *your* current code doesn't work, so it doesn't matter how short it is. First rule of optimization: It has to work. Since Java 8 doesn't have a `CharStream`, you should do it with a normal `for` loop. It only takes 3 lines of code (4 with return statement), and it *works!* – Andreas Oct 07 '16 at 07:55

4 Answers4

13

Yeah, we’re missing a stream method to produce a char array. Maybe a whole CharStream class. In any case, no, you cannot cast between int[] and char[].

In the meantime, it’s getting a long line, but it works:

    return IntStream.rangeClosed('a', 'z')
            .mapToObj(c -> Character.toString((char) c))
            .collect(Collectors.joining())
            .toCharArray();

This gives a char[] containing

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Works like a charm! +1 becuase you arren't a "This wont work"- person :P – TheRealVira Oct 07 '16 at 09:46
  • 1
    `IntStream.range('a', 'z' + 1)` can be replaced with `IntStream.rangeClosed('a', 'z')` – Pshemo Aug 11 '17 at 16:23
  • @Pshemo, thx, it may belong as a comment to the question (from where I took `IntStream.range('a', 'z' + 1)`), but in any case, it’s clearly more readable. – Ole V.V. Aug 11 '17 at 20:33
  • 1
    A downside to this solution is that a String object is created for each array element — this could be a performance / memory consideration for larger arrays. – Mat Gessel Jan 20 '20 at 00:45
2

From Java-11 and onwards , you can use .mapToObj(Character::toString) instead of .mapToObj(c -> Character.toString((char) c)) , so your overall code boils down to :

return IntStream.rangeClosed('a', 'z')
        .mapToObj(Character::toString)
        .collect(Collectors.joining())
        .toCharArray();
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
1

Let's keep it one line then:

return IntStream.range('a', 'z' + 1).mapToObj(i -> Character.valueOf((char) i)).toArray(Character[]::new);

This converts from IntStream, to Stream<Character>. Keep in mind chars and ints are essentially the same in terms of many calculations, so this step may be unnecessary (especially for comparisons).

Edit:

Fixed the above line to be functional, there is a better solution but I'm still trying to find it again. It currently returns a Character[] array.

Without the 1 line restriction it's simple to just remake the array, treating a as your 0 index.

char[] back = new char[('z' + 1) - 'a'];
IntStream.range('a', 'z' + 1).forEach(i -> back[i - 'a'] = (char) i);
return back;
Rogue
  • 11,105
  • 5
  • 45
  • 71
  • that's what I'm talking about! The only problem is, that it returns an `object array` - how can I cast it to an char array? :3 – TheRealVira Oct 07 '16 at 08:11
  • i am not sure if its just my compiler but your solution leads to following error for me: Error: java: incompatible types: java.lang.Integer cannot be converted to char – hasan Oct 07 '16 at 08:12
  • No you're both correct, there's a better way I'll edit it in in just a moment. – Rogue Oct 07 '16 at 08:14
0

You cannot cast int array to char array because there are absolutely different types.

There are 2 possible options:

1) create a char array and copy each value from int array 2) use generic lists or collections. You can simple use it for casting

Alex Klimashevsky
  • 2,457
  • 3
  • 26
  • 58